Release checks and gRPC recovery
You can gate releases with secret checks and image rollback, then contain gRPC failures with interceptors and deadlines before building the filesystem scanner.
Learning outcomes
- You can build a filesystem scanner that detects supported credential patterns without exposing secret values.
- You can identify safe rollback targets using commit-SHA image tags and preserve unrelated Compose configuration.
- You can contain unary and streaming gRPC panics without exposing internal errors to clients.
- You can enforce RPC deadlines while respecting client deadlines and propagating cancellation to downstream operations.
A developer commits a configuration file containing a database password or an API token. The credential can remain accessible in Git history even after the file is corrected. You need a way to detect these mistakes before a release, while also protecting the gRPC service from handler failures and giving operators a reliable way to identify an earlier release.
The three problems need different boundaries. A filesystem scanner protects source code, gRPC interceptors protect request handling, and image-based rollback protects deployed application versions.
Secret scanning
Credential exposure in source control
A secret is a credential that grants access to a system or resource. Your backend can contain several kinds of sensitive values:
- Database passwords used by MySQL.
- Redis authentication credentials.
- GitHub tokens used by automation.
- AWS access keys.
- Private keys used for authentication.
These values can enter source control through .env files, deployment scripts, test fixtures or workflow configuration.
Deleting a credential from the latest commit does not remove it from previous commits. Other branches, forks, CI logs and published images may still contain the original value.
Secret scanning detects recognizable credential patterns before they become part of a release.
There are two useful places to run a scanner.
Local scanning gives a developer an opportunity to correct a mistake before committing. CI scanning checks the repository independently of the developer's machine.
GitHub Actions can run the same scanner as part of a push or pull request workflow. A failed scan can prevent the release workflow from publishing a new image.
The scanner in this project is a small pattern-based utility. It does not authenticate credentials or prove that a detected value is active. It identifies suspicious lines for investigation.
Credential detection rules
A scanner needs explicit rules because different credentials have different formats.
The project uses four detection categories.
AWS access keys
An AWS access key ID begins with AKIA, followed by exactly 16 uppercase ASCII letters or digits.
AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLEThe scanner checks the complete format. A partial match is not sufficient.
GitHub tokens
The supported token prefixes are:
ghp_gho_ghu_ghs_ghr_
Each prefix must be followed by at least 36 ASCII letters or digits.
For example:
GITHUB_TOKEN=ghp_abcdefghijklmnopqrstuvwxyzABCDEF0123Do not assume that every GitHub credential uses the same prefix. The scanner must recognize the formats specified by its contract rather than treating every token-like string as a supported credential.
Private key headers
PEM private keys have recognizable header lines.
-----BEGIN RSA PRIVATE KEY-----
MIIE...
-----END RSA PRIVATE KEY-----The detection rule looks for a line containing both -----BEGIN and PRIVATE KEY-----.
The rule does not need to parse the private key or inspect its contents. Recognizing the header is enough to identify the file as suspicious.
Generic secret assignments
Configuration files often use names such as password, passwd, secret, token and api_key.
Consider these assignments:
password: "hunter2hunter2"
JWT_SECRET=abcdefgh1234
api_key = 'k9d8s7f6g5h4'
DB_TOKEN: zz99yy88xx77A generic rule looks for a case-insensitive occurrence of one of the supported names in an assignment. The separator must be : or =.
The value must contain at least eight characters. Optional spaces and surrounding quotes are allowed, but the value itself cannot contain spaces or quotes.
Generic rules are deliberately broad. They can detect credential assignments that do not follow a specific cloud provider's format, but they can also produce false positives.
Placeholder handling
Configuration files often contain references to environment variables instead of literal credentials.
For example:
JWT_SECRET=${JWT_SECRET}
password: ${DB_PASSWORD}
secret=$SECRET_FROM_ENV
api_key: <your-key-here>These values are placeholders, not literal credentials.
The generic assignment rule must reject values that begin with $, < or {. It must also ignore empty values and values shorter than eight characters.
Do this without disabling generic assignment detection. Otherwise, a real password assignment could pass through unnoticed.
Filesystem traversal with io/fs
A scanner that checks only files in the repository root misses credentials in nested directories.
Go provides the io/fs package for filesystem-independent operations. Its fs.FS interface allows a function to inspect a filesystem without requiring a physical operating-system directory.
Use fs.WalkDir to traverse the supplied filesystem recursively.
The same scanner can receive an operating-system filesystem through os.DirFS or an in-memory filesystem during testing.
For example, testing/fstest.MapFS lets you define files directly in a Go test:
files := fstest.MapFS{
"config/.env": {
Data: []byte("password=hunter2hunter2"),
},
"config/.env.example": {
Data: []byte("password=${DB_PASSWORD}"),
},
}The scanner can inspect these files without creating temporary directories or writing anything to disk.
The filesystem abstraction also changes how you should think about paths. A path provided by fs.WalkDir belongs to the supplied filesystem. You should not convert it into an operating-system path and assume that the input is a real directory.
File exclusions
Scanning every file without exclusions creates unnecessary work and findings that are difficult to investigate.
Apply the following exclusions before inspecting file contents:
.gitdirectories: Skip directories named.gitat any depth.node_modulesdirectories: Skip these directories at any depth.- Example files: Ignore every file whose name ends with
.example. - Binary files: Ignore files containing a NUL byte anywhere in their content.
The binary check must cover the complete file. Checking only the first few bytes does not guarantee that a later NUL byte will be detected.
Read each eligible file before applying text-based matching. If an individual file cannot be read, skip it. A traversal error is different: return it rather than reporting a potentially incomplete scan as clean.
For traversal errors, use error wrapping to add useful context while preserving the original error. Neither error messages nor logs should contain the file's matched content.
Line matching and finding priority
A file may contain several suspicious lines. You should inspect each line independently and assign its original one-based line number.
The scanner evaluates rules in this exact order:
aws-access-keygithub-tokenprivate-keygeneric-secret
Only the first matching rule produces a finding for a line.
Consider this file:
secret=abcdefgh1234
AKIAIOSFODNN7EXAMPLEThe first finding belongs to line 1. The second belongs to line 3. The empty line does not change the original line numbering.
Rule priority matters when a line contains more than one pattern:
AKIAIOSFODNN7EXAMPLE password=hunter2hunter2This line produces one aws-access-key finding, not separate AWS and generic-secret findings.
After scanning all files, sort findings by slash-separated path in ascending lexical order. Within a path, sort by line number.
For example:
a.txt:1: generic-secret
a.txt:3: aws-access-key
b.txt:2: aws-access-keyA finding needs only three pieces of information:
- The relative file path.
- The one-based line number.
- The rule name.
Never store the matched text or credential value in the result.
This boundary matters because scanner output can end up in CI logs, build artifacts and test reports. Printing a credential while reporting that it has been discovered creates another exposure.
When the scan finds nothing, return nil or an empty slice.
Limitations of pattern-based scanning
A pattern-based scanner cannot recognize every possible credential.
An encoded secret, a token split across several lines or a credential assembled dynamically in application code may not match any configured rule.
False positives are also possible. A documentation example can contain a long password-like value without representing an active credential.
Treat findings as investigation signals rather than proof of authentication material.
Rollback with image SHA tags
Release identity
Your backend publishes two container images:
ghcr.io/yashdagar/zomato-api
ghcr.io/yashdagar/zomato-workerA deployment must identify which image version each service should run.
A mutable tag such as latest is not a reliable release identifier. Its contents can change without the tag itself changing.
An image SHA tag identifies an image using the commit SHA associated with its build.
For example:
ghcr.io/yashdagar/zomato-api:a31f9c2
ghcr.io/yashdagar/zomato-worker:a31f9c2The project accepts lowercase hexadecimal commit SHA tags between 7 and 40 characters long.
The difference is important: a31f9c2 identifies a particular source commit, while latest does not identify a particular release.
A SHA tag is a useful release identifier, but it does not automatically guarantee that the registry prevents someone from overwriting the tag. Production systems can also record image digests when they need stronger content identity.
Previous deployed releases
A rollback requires a record of deployed image tags.
Consider this history:
| Release | API and worker tag | Result |
|---|---|---|
| R1 | a31f9c2 | Healthy |
| R2 | b42e8d1 | Healthy |
| R3 | c53f9a2 | Failing |
If R3 introduces a regression, R2 is the release you would investigate as a rollback target.
The image rollback process uses a previous deployed version rather than rebuilding an older application from an arbitrary branch.
A history of deployed tags is ordered from oldest to newest. Repeated deployments of the same tag should not count as separate releases.
For example:
a31f9c2
b42e8d1
b42e8d1
c53f9a2If the current tag is c53f9a2, the previous distinct tag is b42e8d1.
If the current tag is b42e8d1, the previous distinct tag is a31f9c2.
The distinction prevents the planner from recommending the same release as its own rollback target.
There are three important failure cases:
- The history is empty.
- The current tag does not appear in history.
- The current release has no earlier distinct release.
Each case must produce an error. The planner must not invent a fallback tag.
The planner also should not mutate the input history. Release history is evidence used to make a decision, not data that the selection operation should rewrite.
One limitation matters here: a list of deployed tags does not prove that a previous release was healthy. The planner selects an earlier distinct deployment. Operational health information must come from the deployment process.
Validating image references
Before changing a Compose configuration, validate the image reference.
For this project, an image reference contains three independent parts:
ghcr.io/yashdagar/zomato-api:a31f9c2| Part | Value |
|---|---|
| Registry | ghcr.io |
| Repository | yashdagar/zomato-api |
| Tag | a31f9c2 |
The registry must be ghcr.io. The repository must contain exactly an owner and a name, separated by /.
The reference must contain an explicit tag. Valid tags contain 7 to 40 lowercase hexadecimal characters.
References such as these must be rejected:
ghcr.io/yashdagar/zomato-api
ghcr.io/yashdagar/zomato-api:latest
ghcr.io/yashdagar/zomato-api:v1
ghcr.io/yashdagar/zomato-api:A31F9C2
ghcr.io/yashdagar/zomato-api:a31f9c
docker.io/yashdagar/zomato-api:a31f9c2The tag a31f9c is too short. An uppercase hexadecimal tag is also invalid.
Keep parsing and validation separate from Compose modification. A parsed image should preserve the registry, repository and tag independently, and reconstructing its string representation should produce the original valid reference.
Updating compose.prod.yml
The production Compose file determines which image each service runs.
A rollback planner should be able to change one service's image reference without rewriting the entire document.
Consider this API service:
services:
api:
image: ghcr.io/yashdagar/zomato-api:c53f9a2
ports:
- "8080:8080"A rollback to b42e8d1 changes only the image line:
image: ghcr.io/yashdagar/zomato-api:b42e8d1The ports, environment variables, health checks, volumes and every unrelated service must remain unchanged.
There are several details to preserve.
Exact service matching
The selected service must be located under the top-level services: section.
Service names use two-space indentation. Match the complete service name rather than a common prefix.
For example, selecting api must not accidentally select api-docs.
Image repository validation
The Compose pinning operation only accepts existing images under:
ghcr.io/yashdagar/A service using a MySQL image or another registry must not be rewritten as one of your application images.
Interpolated image tags
Compose supports interpolated values such as:
image: ghcr.io/yashdagar/zomato-worker:${WORKER_TAG:-local}The colon in ${WORKER_TAG:-local} belongs to the interpolation expression. It is not the separator between an image repository and an ordinary image tag.
A correct replacement must understand that distinction and replace the existing interpolated tag with the requested SHA tag.
Byte preservation
A planner should preserve the original Compose text as much as possible.
Changing one image line must not alter indentation, whitespace, line endings, unrelated lines or the final newline.
Reconstructing the entire YAML document through a parser and serializer can introduce unrelated formatting changes. A narrowly scoped text transformation is better suited to this contract.
If the requested service does not exist, the service has no image line, or the existing image reference is outside the accepted repository, return an error instead of guessing.
Database compatibility during rollback
Rolling back an image does not automatically reverse database migrations.
Suppose R3 adds a delivery_instructions column and changes the API to depend on it. Restoring the R2 image may fail if the database schema no longer supports the older application.
Application rollback and database rollback are separate operations.
A common migration strategy is expand and contract:
- Expand: Add new tables or nullable columns without breaking the existing application.
- Migrate: Deploy code that can work with both the old and new representations.
- Contract: Remove obsolete columns or behavior after older application versions are no longer needed.
The release rollback planner handles image references and release history. It does not execute a deployment, contact a registry, run Docker commands or reverse database migrations.
gRPC recovery interceptors
Handler failures in the gRPC service
Your API binary exposes the gRPC service on port 9090.
A handler can panic because of a nil pointer, an invalid type assertion or an assumption that does not hold for a particular request.
An unrecovered panic can terminate the Go process.
Recovering a panic in the main server startup function is not enough. A gRPC server handles requests in its own goroutines. The recovery boundary must surround the actual request handler.
Interceptor responsibilities
A gRPC interceptor is middleware that wraps RPC execution.
Instead of implementing common behavior inside every handler, you can apply it around handler invocations.
Go gRPC provides two relevant server interceptor types:
- Unary interceptor: Wraps a single-request, single-response RPC.
- Stream interceptor: Wraps a streaming RPC and receives a
grpc.ServerStream.
A unary interceptor receives a context, request, method information and unary handler. A stream interceptor receives the server, stream, method information and streaming handler.
Both interceptors need to protect the handler invocation itself.
Panic recovery
A recovery interceptor uses Go's defer and recover to contain panics.
The deferred recovery operation must be in the same function scope as the handler invocation. This lets it inspect a panic while the stack is unwinding.
For a unary RPC, the recovery boundary surrounds:
handler(ctx, req)For a streaming RPC, it surrounds:
handler(srv, stream)The handler signatures differ, but the recovery policy is the same.
When a panic occurs, the interceptor must:
- Recover the panic value.
- Record diagnostic information in server-side logs.
- Return no unary response when handling a unary panic.
- Return a generic gRPC error.
Use slog.Error for the recovery log. Include the recovered value under a panic key, the complete RPC method name under method, and the stack trace under stack.
Go provides runtime/debug.Stack() for the stack trace.
The client-facing response must be:
status.Error(codes.Internal, "internal error")The gRPC status code Internal represents an unexpected server failure.
Do not return the panic value, stack trace or internal database details to the client. They belong in server-side diagnostics.
Normal handler execution
Recovery must not change normal handler behavior.
Consider three possible unary outcomes:
| Handler behavior | Interceptor behavior |
|---|---|
| Returns a response and no error | Preserve the response |
| Returns an ordinary error | Preserve the original error |
| Panics | Return nil response and generic Internal status |
Normal returns and ordinary handler errors must not produce recovery logs.
The stream interceptor follows the same policy. A normal stream return remains unchanged, while a recovered panic produces the generic Internal status.
Interceptor ordering
Recovery needs to wrap the execution of the interceptors and handler that it protects.
When registering the optional unary interceptors in the gRPC server, place RecoverUnary before TimeoutUnary and the existing unary interceptors.
Keep the existing authentication and logging behavior intact.
This ordering gives the recovery interceptor a wider boundary than placing it only around the innermost handler. The streaming recovery interceptor has its own streaming handler boundary.
gRPC deadlines
Time limits for RPC requests
A gRPC client should not wait indefinitely for an RPC response.
Suppose one service requests order information from another backend service. If the receiving service becomes slow, the request can continue consuming resources after its result is no longer useful.
A gRPC deadline specifies the latest time at which the client is willing to wait for an RPC to complete.
Go carries this deadline through context.Context.
The server can also enforce a maximum handler duration. This prevents an RPC from running indefinitely when its client does not supply a deadline.
Context propagation
A Go context carries cancellation signals, deadlines and request-scoped values across function boundaries.
The handler must pass its request context to downstream operations rather than replacing it with context.Background().
For example:
func GetOrder(
ctx context.Context,
db *sql.DB,
id string,
) (*Order, error) {
var order Order
err := db.QueryRowContext(
ctx,
"SELECT id, status FROM orders WHERE id = ?",
id,
).Scan(&order.ID, &order.Status)
if err != nil {
return nil, err
}
return &order, nil
}QueryRowContext receives the handler's context. When cancellation reaches the query, the database driver can stop the operation if it supports cancellation.
Redis calls need the same treatment:
result, err := redisClient.Get(ctx, "order:123").Result()
if err != nil {
return err
}The incoming request context must reach both operations.
A deadline on the RPC does not automatically stop work that was started with an unrelated background context. Cancellation is cooperative, so handlers and dependencies must use the supplied context and handle cancellation errors.
Applying a server timeout
A context timeout lets the server impose a maximum duration on an RPC handler.
The optional timeout interceptor receives a configured duration d.
For a positive duration, use context.WithTimeout to derive the handler context:
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()The important behavior is how Go chooses the resulting deadline.
context.WithTimeout preserves the earlier of the parent deadline and the newly requested timeout.
Consider these cases:
| Incoming client deadline | Server timeout | Handler deadline |
|---|---|---|
| None | 2 seconds | Approximately 2 seconds |
| 50 milliseconds | 5 seconds | Client's 50 milliseconds |
| 1 hour | 1 second | Server's 1 second |
The server timeout is an upper bound. It must not extend a shorter client deadline.
Unlike an implementation that creates a timeout only when no client deadline exists, the interceptor should derive a context for every positive timeout. Go handles the comparison between the two deadlines.
Always cancel the derived context after the handler returns. This releases the resources associated with the child context, including when the handler finishes before its deadline.
For a zero or negative timeout, pass the original context through unchanged. Do not introduce a new deadline.
Deadline errors and gRPC statuses
A timeout interceptor must distinguish deadline failures from ordinary handler errors.
When a handler returns context.DeadlineExceeded, the interceptor must convert the failure into a gRPC codes.DeadlineExceeded status.
The check should also recognize wrapped errors. Use errors.Is rather than comparing only the immediate error value.
Other handler errors must pass through unchanged.
There are two important status codes in these examples:
| Status code | Meaning |
|---|---|
codes.Internal | An unexpected server failure, such as a recovered panic |
codes.DeadlineExceeded | The handler could not complete within its allowed time |
Do not classify every handler error as a timeout. A database error, authentication error or missing-order error represents a different failure.
A timeout interceptor also cannot guarantee that every downstream operation will stop. The handler must propagate its context, and each dependency must respect cancellation.
Testing interceptors without a server
You can test recovery and timeout behavior by invoking interceptors directly with fake handlers.
You do not need to start the gRPC server, establish a network connection or serialize a protobuf request.
For recovery, supply a fake unary handler that deliberately panics. Inspect the returned response and error, then verify that the panic value, method and stack trace appear in the logs rather than the client response.
Test the server stream interceptor independently because it receives a different handler signature.
For deadline behavior, supply a handler that records the deadline of the context it receives.
Test the following cases:
- No incoming deadline with a two-second timeout.
- A 50-millisecond client deadline with a five-second timeout.
- A one-hour client deadline with a one-second timeout.
- A handler returning a deadline-exceeded error.
- A zero timeout that must not add a deadline.
These tests verify context propagation and timeout selection without relying on real network latency.
Use Go's testing package to invoke the interceptors with controlled inputs. A table-driven test is useful for checking multiple timeout and error cases with the same test structure.
Exercise connections
The first exercise, Filesystem secret scanner, turns the scanning model into a reusable Go package.
Its filesystem boundary is fs.FS. Its findings contain only paths, line numbers and rule names. Pay particular attention to rule priority, placeholder handling and deterministic output.
The next exercise, gRPC resilience interceptors, applies recovery to unary and streaming handlers and adds a configurable timeout to unary RPCs. Its tests invoke the interceptors directly, so concentrate on their behavior rather than server setup.
Finally, Release rollback planner uses pure Go operations to validate image references, update a selected Compose service and find the previous distinct deployed tag. The planner calculates a rollback target but does not perform a deployment.
The three extensions address different release risks. Keep their boundaries clear: detecting a credential does not rotate it, recovering a panic does not fix the underlying handler, and selecting an earlier image does not reverse database migrations.
Check your understanding
A configuration file contains these two lines:
password: ${DB_PASSWORD}
password: hunter2hunter2What should the scanner report?
References
Everything above is explained on this page; these are where it comes from (Go, gRPC).