Extending CoSec
For developers who need behavior CoSec does not ship. This page lists every extension point of the 8.0 pipeline and control plane, what each one must guarantee, and how the starter picks it up. The guarantees come from the architecture invariants: an extension that blocks a thread or hides a failure weakens every decision.
Extension points
With the starter you extend CoSec by declaring a Spring bean. Some extension points collect every bean of their type; the others are single beans that replace the starter's default (@ConditionalOnMissingBean). Without Spring, build the pipeline over your document store with Pipeline.builder(authenticator, store), pass your implementations to the builder (memberships, attributes, listener, rateLimiter, ids), and call awaitDocuments() before the first request. The builder is @ExperimentalCoSecApi (Stability levels); tests get a real pipeline from PipelineFixture (cosec-testkit).
Extension points are implemented in Kotlin. The data plane's ports are suspend functions, and the ids (TenantId, AppId, PrincipalId) are value classes, so a method with one in its signature has a mangled JVM name (memberships-hPxUw84) that Java cannot declare. A Java application configures the starter, reads the caller, and checks with checkMono (WebFlux) or checkBlocking (WebMvc); the pipeline, token issuing and revocation suspend, which Java cannot call. It writes its implementations of CoSec's ports in Kotlin. Durations, instants and clocks in public and SPI signatures are java.time's, never kotlin.time's (KotlinTimeSignatureTest).
| Extension point | Module, package | Implement it to | The starter takes |
|---|---|---|---|
Authenticator | cosec-spi, spi.authn | Accept another kind of credential, or replace token and API key authentication. | one bean, replacing the built-in one |
TokenStore, RevocationReader | cosec-spi, spi.token | Keep revoked tokens somewhere other than Redis. | one bean of each |
ApiKeyReader | cosec-spi, spi.apikey | Look API keys up somewhere other than memory or Redis. | one bean |
MembershipProvider | cosec-spi, spi.membership | Supply the roles and attached policies of principals whose credential does not carry them: tokens with the provider marker, and every API key. Say whether a principal is known and active. | one bean; required with API keys |
MembershipLoader | cosec-cocache, cocache | Load the memberships that CoCacheMembershipProvider keeps in each instance's memory, never in Redis (MEM-5). | one bean, wrapped in CoCacheMembershipProvider when there is no MembershipProvider |
AttributeProvider | cosec-spi, spi.attribute | Give conditions external attributes (ext.<provider>.<name>). | every bean |
AuditEventSink | cosec-spi, spi.audit | Receive the flat audit record of each decision. | every bean, as a BEST_EFFORT listener |
RateLimiter | cosec-spi, spi.ratelimit | Count rate limit permits somewhere other than Redis or memory. | one bean, replacing the built-in one |
SnapshotDocumentStore | cosec-spi, spi.snapshot | Keep policy documents somewhere other than Redis. Experimental in 8.0 (@ExperimentalCoSecApi): its shape follows its one backend, and a batched or store-wide conditional read is planned. | one bean, without cosec-cocache |
IdGenerator | cosec-spi, spi.id | Give request, token and change ids your own format. cosec-cosid implements it over CosId 5. | one bean, replacing RandomIdGenerator |
Authentication | cosec-login, login | Check another kind of login credential and say what its token holds. Throw to refuse. | every bean, by the credential type it supports |
TenantSwitch | cosec-login, login.token | Say what a user holds in the tenant, and the app, it switches to, and which app the new token is for (Switching tenant and app). Throw to refuse. | none: declare SwitchTenantAuthentication(tokenVerifier, tokenFamilies, tokenRevocation, YourCredentials::class.java, yourSwitch) as an Authentication bean; your credentials carry the token pair the switch presents |
MembershipRefresh | cosec-login, login.token | Say what a user holds now when its token is refreshed, so changed roles apply (Refreshing tokens). Throw a TokenVerificationException to refuse (401); any other exception is an error (500); null keeps the claims. | none: pass it to RefreshTokenAuthentication; the starter's refresh route takes a MembershipRefresh<RefreshTokenCredentials> bean, or startup fails until cosec.jwt.session.memberships-on-refresh=from-token keeps the token's memberships (STA-8) |
TokenConverter | cosec-login, login.token | Issue tokens in another format. | one bean, replacing JwtTokenConverter |
SocialUserPrincipalConverter | cosec-social, social | Turn a provider's user into your principal. | one bean, replacing DirectSocialUserPrincipalConverter |
SocialStateStore | cosec-spi, spi.social | Keep the OAuth states social login issues somewhere other than Redis: put a state with its binding's hash, and take removes it atomically, so a state is used once. Both suspend: over a blocking client, make the calls on a dispatcher of your own. Throw when the store fails. InMemorySocialStateStore (same package) is one for tests and a single instance. | one bean, replacing cosec-cocache's RedisSocialStateStore |
BlacklistSource | cosec-runtime, runtime.attribute | Say which principals, addresses and devices are blocked. | one bean, wrapped in BlacklistAttributeProvider |
DecisionListener | cosec-runtime, runtime.event | Observe every decision: audit, alerting, analytics. | every bean |
BridgeContextContributor | cosec-runtime, runtime.event | Carry a thread-local context (logging, tracing) into the pipeline. | every bean |
ProblemRenderer | cosec-runtime, runtime.http | Write the body of a refusal in your framework's own problem catalog (Problem renderer). Experimental. | one bean, replacing CoSec's own body; two fail startup |
ChangeListener | cosec-control, control.audit | Observe or gate control-plane changes. | every bean, with cosec-control |
ControlStore | cosec-control, control.store | Keep the control plane's records (revisions, change requests, staging slots) somewhere other than in CoCacheControlStore. The control plane itself starts only with cosec-cocache, whose Redis stores keep the published documents: this port does not change that. Experimental, with its records and the shadow window ports. | one bean, with cosec-control and cosec-cocache |
| Route maps | cosec-document, document.route | Give requests service:verb actions on typed resources. | cosec.authorization.routes.location |
Packages are under me.ahoo.cosec. The ports whose signatures need only the model and the contracts live in cosec-spi, with their value types and in-memory implementations (InMemorySnapshotDocumentStore, InMemoryMembershipProvider, InMemoryApiKeyStore); it depends on cosec-model, cosec-api, cosec-annotations and kotlinx-coroutines only, so an implementation of one of them needs nothing else from CoSec. The shadow window ports (CandidateStore, ShadowReportSink, ShadowReportReader, in spi.shadow) are among them: their candidates and reports are plain values. A port whose signature carries a layer's own types stays with that layer: DecisionListener takes the runtime's DecisionEvent, and ControlStore and ChangeListener the control plane's records and events.
Each of these interfaces carries @CoSecSpi: changing one, rather than implementing it, breaks every application that implements it (Stability levels).
The adapters themselves call a RequestGate (cosec-runtime): the Pipeline, or, on a service behind a CoSec gateway (cosec.pipeline.mode=gateway), IdentityGate. It is not an extension point: both build every outcome through StatusMapping, and a gate of your own would be a second decision path. The compiler holds this: implementing RequestGate requires the @InternalCoSecApi opt-in (@SubclassOptInRequired), which applications never give.
Two beans of the starter's login are replaceable too, though they are not extension points: CompositeAuthentication, which the login routes use, and TokenCompositeAuthentication, which issues the token pair after it. Each backs off when the application defines a bean of the same type, so a bean of your own is the only one (the starter's CompositeAuthentication is @Primary, and two would be ambiguous). The control plane's authorization beans are the ones that are not replaceable on purpose: startup fails when another exists.
Pipeline outside the adapters
A transport of your own (an internal port, a WebSocket handshake, a custom server) reads the request into HttpFacts and calls Pipeline.evaluate, as the web adapters do. It answers an Outcome. A refused request has a status, a problem to write with ProblemEncoder and headers to set. A permitted one (proceed) carries the context of the request, Outcome.security?.securityContext: the SecurityContext your code reads, and the only kind an AuthorizationChecker accepts (Checks in code):
pipeline.evaluate(facts).use { outcome ->
if (!outcome.proceed) {
return respond(outcome.status, outcome.headers, outcome.problem?.let(ProblemEncoder::encode))
}
val security: SecurityContext = checkNotNull(outcome.security).securityContext
val mayCancel = AuthorizationChecker(pipeline).check(security, "order:cancel", "order/42")
handle(security, mayCancel)
} // the request has ended: a check of `security` is now false (PIP-26)Closing the Outcome ends the request (PIP-26): every later check of its context is false, as after a web adapter's response. Close it when the response is complete. For a response that outlives the handler (a streamed body, a WebSocket session after its handshake), close it from the response's completion callback, not when the handler returns, or the request ends while the stream is still being written and the checks it makes are false:
val outcome = pipeline.evaluate(facts)
connection.onClose { outcome.close() } // completion, failure and cancellation alikeClosing a refused Outcome does nothing, and closing twice is harmless. A transport that never closes it leaves the request in progress for as long as its context is held. CoSec's web adapters end the requests they bind themselves: an application that uses them never closes anything.
The context is for that request only, like the one a web adapter binds. Pipeline.evaluate, Outcome, HttpFacts and RequestSecurity are @ExperimentalCoSecApi (Stability levels). Running the pipeline on such a port is how a service verifies a token it receives there, rather than calling TokenVerifier by hand, which skips the revocation check (Verifying a token outside the pipeline).
Stability levels
Every public declaration of a published module is in one of four levels. The markers are in cosec-annotations (me.ahoo.cosec.annotations):
| Marker | What it promises | What you do |
|---|---|---|
| none | Stable. From 8.0 GA on, removing or changing it is a breaking change, made only in a major release. | Use it. |
@CoSecSpi | An interface applications implement, not only call: the extension points above. Stable like the rest, and a member added in a minor release comes with a default body, so an implementation keeps compiling. | Implement it. |
@ExperimentalCoSecApi | Public, but it may change or go away in a minor release; the release notes say so. Today: the public API of cosec-testkit (PolicyTestKit, PipelineFixture, AttributeRequests, EngineOutcome and their exceptions); assembling a pipeline without Spring (Pipeline.builder, PipelineBuilder and its settings PipelineSettings, SnapshotSettings and IdentityForwardingSettings, Pipeline.behindGateway with GatewayIdentitySettings, Pipeline.evaluate and awaitDocuments, RequestGate, HttpFacts, Headers, Cookies, Outcome, Problem, ProblemEncoder, ProblemRenderer, RequestSecurity); the evaluation trace (DecisionEvent.evaluationTrace, me.ahoo.cosec.engine.trace); and the control plane's store and shadow window ports with their records (Control store). | Opt in with @OptIn(ExperimentalCoSecApi::class), or the compiler warns. |
@InternalCoSecApi | Public only so that CoSec's own modules can call each other. No promise: it may change in any release. | Never use it. Opting in is required at error level, and only CoSec's own sources do. |
The build keeps these promises. Every published library module stores its public ABI in a dump file, api/<project>.api in its directory (core/spi/api/spi.api for cosec-spi), and check runs the Kotlin Gradle plugin's checkKotlinAbi, which fails when the compiled module no longer matches its dump. cosec-migrate keeps no dump: it is a command-line tool, its contract is the command line, and its classes are not a library API. @InternalCoSecApi declarations are left out of the dumps; experimental ones are in them, so their changes show in review too. A dump lists signatures, not annotations, so which interfaces are SPIs is read from the sources, the API docs and this page, and SpiMarkerTest (test/architecture) fails when a public interface of cosec-spi, or a type the table above names, lacks @CoSecSpi.
To change a public signature on purpose, regenerate the module's dump and commit it with the change:
./gradlew :spi:updateKotlinAbiReview the dump's diff like code: an added line is a new API; a removed or changed line breaks the callers or the implementations of that declaration. From 8.0 GA on, a pull request that removes or changes a line of a dump is a breaking change and its title carries ! (CONTRIBUTING.md). The one exception is a line of an @ExperimentalCoSecApi declaration: removing or changing it is not a breaking change and needs no !, and the pull request description says which experimental declarations it changes.
Sets that grow
Exhaustive matching over a closed set stops compiling when a minor release adds a member, and an already compiled binary throws NoWhenBranchMatchedException on the new value. So every extension treats these as open: a when over one has an else, and a listener or store never relies on the set being complete.
| Set | Grows by |
|---|---|
AuthnResult.RejectReason | a new reason, such as a new token check |
ProblemType | a new problem, such as 413 or 415 |
Obligation | a new kind of obligation |
Cause | a new reason a decision is Indeterminate, such as a new port that can fail; a DecisionListener reads it from a decision event |
ChangeEvent.Kind | a new kind of change event |
OutcomeSummary.Reason | a new reason an outcome was answered, such as the refusal of a new kind of obligation |
A set not listed here does not gain a member after 8.0 GA. A public data class is only ever a value that cannot grow, a record with a fixed shape (PublicApiStabilityTest reads the reviewed list); a record that can grow is a plain class, so a new field is a new constructor. The decision values (Decision, Cause, Obligation, ViewVersion) are plain classes for that reason: no copy, no destructuring.
Rules every extension follows
The pipeline calls every SPI on the request path, often on a Netty event loop. The login contracts run on your login endpoint, on the same threads. Every SPI here follows the same contract:
- Never block the calling thread. The SPIs are
suspendfunctions (the snapshot store returnsCompletableFutures). A suspending client is fine. An implementation over a blocking client (JDBC, a blocking HTTP client) moves the call to its own bounded executor withrunInterruptible(myDispatcher) { ... }, sized for that dependency:Dispatchers.IO.limitedParallelism(n)or an executor of your own, asJustAuthProviderdoes. A bareDispatchers.IOis shared with everything else in the process, andRuntimeBoundaryTestforbids it incosec-runtime. - Stop when cancelled. Timeouts are cooperative: at an SPI's timeout, or at
cosec.pipeline.timeout, the pipeline cancels the call and waits for it to return before it answers503.withContext(myDispatcher)cannot stop a blocking call, so a JDBC query that hangs for 30 seconds holds the request for 30 seconds, not for its 300 ms timeout, and on WebMvc it holds a request thread too.runInterruptibleinterrupts the thread on cancellation; give the client its own timeouts as well (a JDBC query timeout, an HTTP read timeout) for calls that ignore interruption. - Report failure by throwing. Never answer "nothing" for a lookup that failed: an empty membership list, a missing attribute or "not revoked" can each turn a deny into a permit. The pipeline turns a thrown exception or a timeout into
Indeterminate, which answers503unless a DENY matches. - Answer ids that are text. An id an SPI gives (a principal, a tenant, a credential id, a role, a space, a policy id) must not hold an unpaired UTF-16 surrogate: a Redis key would hold
?in its place and share another id's key (IDN-10).AuthenticatedPrincipalandApiKeyrefuse one when made, so an authenticator or an API key store that gives one throws, and aMembershipProvideranswer with one fails: each is a503.Identifiers.isWellFormed(cosec-model) is the test;Identifiers.printablewrites an id into an exception message or a log line without letting it forge a line. - Name someone. A principal id is never blank, empty or white space only (
IDN-38):PrincipalIdrefuses one when made, so an authenticator that gives one throws, which the pipeline answers503, as above. Report a credential that names no one asRejectedinstead, so the client is told its credential is invalid. Ids are not trimmed:" alice "is an id of its own. - Do not catch cancellation. A client that goes away cancels the request's coroutine. Rethrow
CancellationException, and do not userunCatchingaround a suspending call. - Keep it cheap. Each call has a timeout (see Configuration); the whole request has
cosec.pipeline.timeout. A local answer that does not suspend costs no thread switch and no timer.
Authenticators
Authenticator turns a request's credentials (Credentials.token, Credentials.apiKey) into an AuthnResult:
| Result | When | What happens |
|---|---|---|
Authenticated(principal, method) | The credential is valid. | The request is evaluated as that principal; method, an Identity.Method (JWT, API_KEY or a name of your own), goes to audit. |
Anonymous | No credential. | The request is evaluated as the anonymous principal. |
Rejected(reason) | The credential is invalid, expired or revoked. | The request is evaluated as anonymous; a deny answers 401 with that reason. |
Unavailable(cause) | A dependency failed. | 503. A thrown exception is treated the same way. |
An AuthenticatedPrincipal names its id, tenant, app (the app its credential declares, Apps; left out, none), membership source (the token's claims, or the membership provider), attributes and credential. Conditions read the attributes as subject.attributes.<name>. The principal keeps a read-only view of the map you hand over, with no copy, and every further check of the request decides on it: do not change the map afterwards, and put only immutable values in it (strings, booleans, numbers, and immutable lists and maps of them). credential (Identity.Credential: method JWT or API_KEY, the credential's id and its expiry, never its value) is what a gateway forwards with the identity: on a gateway, a principal without one is permitted but forwarded to no backend as authenticated, and one whose credential has no expiry fails the request with 500.
Whether break-glass bindings apply is decided by provenance: only a token CoSec's own JwtTokenVerifier verified gets them, through TokenAuthenticator. A principal your authenticator returns, with a credential of its own method (such as Identity.Method("ldap")) or none, never gets break-glass, and nor does a token a TokenVerifier of your own accepts, even through TokenAuthenticator (its credential is then named after the authenticator's method, token by default). The method JWT is reserved for CoSec's token: an AuthenticatedPrincipal you construct with it is refused (IllegalArgumentException, a 503), so no authenticator can pass for CoSec's token by its name (BRK-8).
The control plane reads two more facts of the principal for approvals (Testing policies). workload (IDN-34): true for an API key (apiKey: CoSec's API key authenticator sets it, and a credential of the method API_KEY counts as one whoever made it) and for a credential of the method SERVICE (service, a service's own identity), whoever made it; a workload never approves and is never the trust root. A principal of yours is a person's to CoSec unless its credential is named api-key or service. So a machine client your authenticator proves under a method of its own (oauth-client, say) and grants cosec:approve can approve changes and be the trust root: two such credentials make four eyes. An authenticator of workloads names its credential Identity.Credential(Identity.Method.SERVICE, id, expiresAt) (or API_KEY) in the principal it builds, which makes the principal a workload, and gives it neither cosec:approve nor cosec:platform-admin (DR1-C-3; telling a person by provenance alone is 8.1's). The credential's id: an approval records it, and one without an id does not count. A principal you construct has no issuedAt, so any revocation of its tokens (subjectRevokedBefore) takes its approvals back.
An authenticator sees only what the pipeline reads as credentials: the token (the Authorization header, else the query parameter when cosec.pipeline.allow-query-token is on, else the cookie when cosec.pipeline.allow-cookie-token is on) and the API key header (cosec.pipeline.api-key-header).
The starter's default is a CompositeAuthenticator: a request with an API key is judged by the API key authenticator alone (when cosec.api-key.enabled), any other request by the JWT TokenAuthenticator. Your Authenticator bean replaces all of it, and with it every cosec.authentication.revocation.* setting: the starter hands those to the TokenAuthenticator it builds, and a TokenAuthenticator you build has the constructor's defaults, a skew of 5 seconds and fail-closed: false, whatever the operator set. To accept another token format and keep the built-in ones, build them yourself, take each setting from where the starter does, and delegate:
@Bean
fun cosecAuthenticator(
algorithm: Algorithm,
verifier: ObjectProvider<TokenVerifier>, // your own verifier, if you registered one; the starter prefers it
tokenStore: TokenStore, // cosec-cocache's store: its `reader` is the starter's revocation reader
unchecked: UncheckedRevocations, // the starter's counter of tokens accepted without a revocation check
keys: ApiKeyReader, // the Redis keys' reader; with the in-memory store, InMemoryApiKeyStore.reader
@Value("\${cosec.authentication.revocation.skew:5s}") skew: Duration,
@Value("\${cosec.authentication.revocation.fail-closed:false}") failClosed: Boolean,
): Authenticator {
val builtIn = CompositeAuthenticator(
TokenAuthenticator(
verifier.getIfAvailable { JwtTokenVerifier(signing, skew) },
(tokenStore as CoCacheTokenStore).reader, // a RevocationReader bean of your own, if you have one
revocationSkew = skew,
acceptUnavailableRevocations = !failClosed, // true accepts a token while revocations cannot be read
unchecked = unchecked,
),
ApiKeyAuthenticator(keys),
)
val sessions = SessionTokenAuthenticator() // your own Authenticator for "Session ..." tokens
return Authenticator { credentials ->
if (credentials.token?.startsWith("Session ") == true) {
sessions.authenticate(credentials)
} else {
builtIn.authenticate(credentials)
}
}
}An operator who set cosec.authentication.revocation.fail-closed: true is open again the moment the recipe forgets the line that reads it, and nothing logs it: keep the three settings, or the revocation hardening is lost (the exception).
A TokenVerifier of your own returns a VerifiedToken (me.ahoo.cosec.spi.token), an immutable value built from the claims it verified: id, principal, tenant, app (the token's aud), roles, policies, attributes, its times and membership marker. Its constructor throws TokenVerificationException for claims that no token may carry (an id beginning with (, a blank subject, an empty tenant, an unpaired surrogate, an impossible app), so verify refuses them whichever verifier read them.
A TokenVerifier is pure computation by contract: no I/O and nothing that blocks, since the pipeline calls it on the request's thread. Whether a token was revoked is not its question: TokenAuthenticator, refresh (RefreshTokenAuthentication) and TokenRevoker read it through the suspending RevocationReader, all with one judgement, TokenRevocation. Only CoSec's own verifier's tokens may use break-glass. A token with an act claim must never become a principal (IDN-4): a TokenVerifier of your own throws DelegationUnsupportedException for it, which TokenAuthenticator turns into a token-invalid refusal, and an Authenticator of your own that reads tokens itself returns AuthnResult.Rejected(DELEGATION_UNSUPPORTED) instead of a principal for its sub. How tokens, claims and memberships work for users is in Authentication.
Credentials and revocation
| Extension point | Contract |
|---|---|
TokenStore | The write side of revocation, called by CoSec's own TokenRevoker, never by your code: revoke(tokenId, ttl) takes a token's jti (VerifiedToken.id), never the token, so revoke(accessToken, ttl) writes a key named after a live credential and revokes nothing. An application logs a user out, or revokes a principal, through TokenRevoker (Logout and revocation). The store's methods are revoke(tokenId, ttl), revokeSubject(tenant, principal, issuedBefore, ttl), both suspending and non-blocking. An entry must outlive the refresh token it revokes. A store that cannot revoke every token of a principal throws from revokeSubject, so an emergency revocation never silently does nothing. |
TokenFamilyStore | The sessions of refresh tokens (Sessions): create, read, and replace a family only over the version read, atomically across instances. A failed read or an unconfirmed write throws. Read and written on login, refresh and logout only. A family's expiresAt is an upper bound: drop a record once it can no longer refresh, as CoSec's stores do after the refresh token validity. Keep TokenFamilyStore.SESSIONS_PER_PRINCIPAL sessions per principal and tenant, those that began last: create of one more deletes the earliest (IDN-35). Save every member of a family, root included: a switch reads it back and is refused without it (IDN-36). |
RevocationReader | The read side, called on every authenticated request: isRevoked(tokenId), subjectRevokedBefore(tenant, principal). Both suspend and must not block. Each must answer or fail within its own bound, throwing RevocationUnavailableException when the store cannot be read in time: CoSec gives your reader no budget but the authenticator's, and a read that never ends makes the request 503 at the authentication timeout (20 % of cosec.pipeline.timeout), whatever cosec.authentication.revocation.fail-closed says. CoSec's own reader bounds each read with the revocation read timeout (30 % of the authentication timeout). |
ApiKeyReader | findByHash(hash): ApiKey?, suspending. Return null for an unknown key; throw when the lookup fails (the request answers 503). |
With cosec-cocache, the starter wires CoCacheTokenStore and its reader. Without it, JWT fails startup unless you register a TokenStore and a RevocationReader (or set cosec.jwt.enabled=false). Registering RevocationReader.NONE is an explicit choice to revoke nothing.
A RevocationReader reports what it knows: when its store cannot be read, it throws RevocationUnavailableException, never "not revoked". What that means is the caller's: TokenAuthenticator, verifying a request's token, lets the token through, one of the two documented exceptions to failing closed; refresh, which issues a token, fails (IDN-14). Anything else a RevocationReader throws answers 503. The exceptions are listed in the security model.
Memberships
A token carries a principal's roles and attached policies as claims, or, when they change often or do not fit, the provider marker instead. An API key never carries them (RFC 0009 §4). For those principals the pipeline asks the MembershipProvider:
fun interface MembershipProvider {
suspend fun memberships(tenant: TenantId, principal: PrincipalId): MembershipAnswer
}- Answer
MembershipAnswer.Known(Memberships(Memberships.Source.PROVIDER, roles, attachments)): roles by space (SpaceId.DEFAULTfor the default space) and attached policy ids, in order. Any other source is rejected. - Answer
MembershipAnswer.Unknownfor a principal you do not know, and memberships withactive = falsefor one that is deactivated: the credential is then refused (token-invalid), as if its authenticator had rejected it (IDN-3). Do not answer empty memberships for an unknown principal: that is a known principal with no roles, and its API keys would keep working. A sealed answer, so that a provider has to say which it means. - Throw when the lookup fails. A failure, a timeout (the membership timeout, 10 % of
cosec.pipeline.timeout) or a missing provider makes the request503, never "unknown" and never "no roles": no roles would also mean that no DENY bound to a role applies. - An API key's cap (
MembershipSource.Provider.cap) is applied by the pipeline'sMembershipResolver, after your answer: answer the principal's memberships, never a key's.
InMemoryMembershipProvider (cosec-spi) is for tests; it answers Unknown for a principal it was not given. CoCacheMembershipProvider (cosec-cocache) keeps what your MembershipLoader answers in each instance's memory, never in Redis, so each instance asks your loader for the principals it serves (MEM-5); MembershipLoader.load follows the same contract, Unknown is not cached, and a load that takes longer than its fill timeout (in the starter the membership timeout, 10 % of cosec.pipeline.timeout) fails, so that the next request retries. Call its invalidate when a principal's memberships change. The starter registers CoCacheMembershipProvider when you declare a MembershipLoader bean and no MembershipProvider; otherwise declare the one you want as a bean. With API keys on, one is required (IDN-6).
External attributes
Conditions read the request, the principal and the scope directly. Anything else (a department from a directory, a risk score, the client's region) comes from an AttributeProvider:
@Component
class DirectoryAttributeProvider(private val directory: DirectoryClient) : AttributeProvider {
override val attributes = listOf(AttributeDeclaration("ext.directory.department", AttributeType.STRING))
override val timeout: Duration = Duration.ofMillis(200) // java.time; null uses the attribute timeout (6 % of cosec.pipeline.timeout)
override suspend fun fetch(request: AttributeRequest, names: Set<String>): Map<String, Any> {
if (!request.subject.authenticated) {
return emptyMap() // absent: a comparison with it is false
}
val department = directory.departmentOf(request.tenant.value, request.subject.id) // suspends, throws on failure
return if (department == null) emptyMap() else mapOf("ext.directory.department" to department)
}
}{ "eq": ["ext.directory.department", "finance"] }- Declare every attribute as
ext.<provider>.<name>with its type:STRING,BOOL,STRING_SETorIP. Each path is declared once across all providers. The declarations form the attribute catalog that documents compile against: a policy that reads anext.path nobody declares does not compile. A platform document may also declare the catalog, so the control plane and every instance agree. - Register the same providers on every host. The control plane checks a change against the platform's declarations and its own host's providers, and every instance compiles against its own. A provider missing on one instance makes a change it reads fail there: the instance reports
CANDIDATE_ERRORand blocks the shadow window (Deploying the gateway server). - Values. Return values by path, of the declared type: a
String, aBoolean, aSet<String>, or forIPanIpAddress(cosec-model;IpAddress.parsereads one from text). A path left out is absent. A value of the wrong type, a thrown exception or a timeout makes the attributes asked for unavailable, and each statement that reads them follows itsonMissingsetting (Policy language). - Stages. A stage-B attribute (the default) is fetched only when the engine's plan says this request could read it, after the scope is resolved. A stage-A attribute is fetched on every request, before the scope, together with the memberships. Use stage A only for attributes that decide what is loaded, as the blacklist does. An
AuthorizationCheckercheck asks for what its own action and resource can read, in both stages: a stage-A provider is asked again then, still without the scope. - What a provider sees.
AttributeRequestholds the tenant, the subject, the resolved scope (null in stage A), the action, the resource, the client address, the request id and the device id, never another attribute's value.
Testing a provider. AttributeRequests (cosec-testkit, @ExperimentalCoSecApi) builds the request a provider is asked with. Only the pipeline constructs a resolved scope, so the kit resolves it with the pipeline's own resolver, from the principal's roles, the space the request selects and the host's app:
@OptIn(ExperimentalCoSecApi::class)
class DirectoryAttributeProviderTest {
private val provider = DirectoryAttributeProvider(FakeDirectory(mapOf("acme/alice" to "finance")))
private val alice = PipelineFixture.Principal("alice", tenant = "acme", roles = setOf("reader"))
@Test
// <Unit>: JUnit skips, without a word, a test method that returns a value
fun `reads the department of the principal`() = runBlocking<Unit> {
val request = AttributeRequests.of(Action("order", "read"), Resource("order", "7", emptyMap()), alice)
val values = provider.fetch(request, setOf("ext.directory.department"))
check(values == mapOf("ext.directory.department" to "finance"))
}
}AttributeRequests.beforeScope is the request of stage A, without a scope. A scope the pipeline would reject (a space the principal has no role in, another app than the host's) throws: no stage-B provider is ever asked with one.
The blacklist is a stage-A provider: BlacklistAttributeProvider(source) declares ext.blacklist.principal, ext.blacklist.ip and ext.blacklist.device, and a request one of them blocks meets the built-in DENY cosec:blacklist. Implement BlacklistSource.contains(kind, value) over your store (principals are <tenant>:<principal id>; an address is asked for in its canonical form, 2001:db8::1 for any spelling of it and 192.0.2.1 for ::ffff:192.0.2.1, so keep blocked addresses in that form), or use InMemoryBlacklistSource, which keeps them so, and declare the source as a bean: the starter wraps it in a BlacklistAttributeProvider. Without one, startup logs No BlacklistSource bean: requests are not checked against a blacklist (ext.blacklist.*). at INFO. A source that fails never means "not blocked": the request is 503 unless a DENY matches.
With cosec-ip2region, the starter registers Ip2RegionAttributeProvider (ext.ip2region.country, .province, .city, .isp).
Decision listeners
A DecisionListener observes every DecisionEvent: the outcome and status, the decision and the statement and binding that decided it, the document revisions, the subject, scope, action and resource, the status (never the value) of each external attribute, and the trace. It cannot change the decision.
@Component
class BreakGlassAlerts(private val pager: PagerClient) : DecisionListener {
override val name = "break-glass-alerts" // unique among the listeners
override suspend fun onDecision(event: DecisionEvent) {
if (event.breakGlass) {
pager.page("break-glass used by ${event.subject.tenant}/${event.subject.id}")
}
}
}delivery | Delivered | A failure |
|---|---|---|
BEST_EFFORT (default) | Queued without suspending into the listener's own bounded queue, handled off the request path. A full queue drops the event. | Logged and counted; the response is unchanged. |
REQUIRED | Before the response, together with the other REQUIRED listeners, within 20 % of cosec.pipeline.timeout. | Turns a permit into 503; any other outcome keeps its status. |
- A permit through a break-glass binding needs at least one REQUIRED listener, or it is a
503. - A REQUIRED listener should be idempotent by
event.id: a write that timed out may still have succeeded. - Every
DecisionListenerbean is registered, in@Orderorder, and so is everyAuditEventSinkbean that is not also a listener, as aBEST_EFFORTlistener named after the bean. The starter adds the audit log (LoggingAuditListener, unlesscosec.audit.enabled=false), and, with their features,MetricsListener,TracingListener,KafkaAuditListenerand the shadow listener. Events, metrics and spans are described in Observability. event.evaluationTraceholds the engine's trace atcosec.pipeline.trace-level; it is null atoff, the default.- On shutdown, queued events are still delivered for up to a sixth of
spring.lifecycle.timeout-per-shutdown-phase. - Testing a listener:
PipelineFixture(cosec-testkit) takeslistenersand delivers them the events the pipeline makes, so a test reads real events, never hand-built ones: a REQUIRED listener has the event beforeevaluatereturns, a BEST_EFFORT one once the fixture is closed (Testing your code against a real pipeline).
Rate limiters
RateLimiter counts the permits of a permit's rate limit obligations:
fun interface RateLimiter {
suspend fun tryAcquire(ruleId: String, bucket: String, limit: RateLimitSpec): RateLimitResult
}Spend one permit of limit from bucket of rule ruleId and report what is left; limit.limitPerWindow and limit.windowMillis give the sliding window both built-in limiters use, and limit.resultOf(...) (me.ahoo.cosec.spi.ratelimit.resultOf) builds the result. Throw when the backend fails: the rule's strictFailure then decides between 503 and skipping the rule. With cosec-cocache and a ReactiveStringRedisTemplate, the starter registers ReactiveRedisRateLimiter, which counts across instances; otherwise the per-instance LocalRateLimiter. Your bean replaces both. A pipeline built with Pipeline.builder counts in a LocalRateLimiter of its own unless given one with rateLimiter(...). Rules, buckets and headers are in Rate limiting.
Snapshot document stores
SnapshotDocumentStore (@ExperimentalCoSecApi in 8.0: its shape follows its one backend, and a batched or store-wide conditional read is planned) is where SnapshotSource reads the platform, app and tenant documents:
read(key)may answer from a local copy (report its maximum age aslocalCopyMaxAge);readIfChanged(key, known)must read the store of record and answerUnchangedwhen the digest matches;subscribe(listener)reports changes after they are readable.Every method returns without blocking and never throws: a failure completes the future exceptionally. A stored value that cannot be decoded carries a
SnapshotFormatExceptionin its cause chain.Never delete a document. A key that once had a document and then reads as absent fails closed.
A document is its bytes: the whole JSON document, header included. Return the
SnapshotDocumentSnapshotDocuments.read(bytes)(cosec-document) makes of them, which reads the header from the bytes; nothing else makes one, so a store cannot report a revision its bytes contradict (SNP-12). A store that keeps the bytes:kotlinoverride fun read(key: SnapshotKey): CompletableFuture<SnapshotRead> = fetch(key).thenApply { bytes -> bytes?.let { SnapshotRead.Present(SnapshotDocuments.read(it), SnapshotDigest(sha256(it))) } ?: SnapshotRead.Absent }A digest is a
SnapshotDigest: 32 bytes of SHA-256, named by its algorithm, and nothing else (a SHA-1, a version number or an ETag is refused when made, so every read fails closed). Hash the stored bytes, or whatever changes when the document does; only your store interprets it. Its text form, in the control API and in events, isSHA-256:<64 hex>.
With cosec-cocache, the starter uses RedisSnapshotDocumentStore, and the control plane writes through the same Redis. Without it, the starter registers an InMemorySnapshotDocumentStore; put documents into it with put(key, SnapshotDocuments.read(bytes)), or declare your own SnapshotDocumentStore bean instead. Requests fail closed until a platform document is there.
Ids
IdGenerator (generate(): String) makes the ids of what CoSec creates: request ids (CoSec-Request-Id, and the rid a gateway forwards in CoSec-Identity), decision event ids, token ids (jti) and control-plane change ids. Without one of yours, CoSec uses RandomIdGenerator: random version 4 UUIDs drawn from ThreadLocalRandom, which never blocks, rather than from SecureRandom, which can.
- An id is unique across every instance that shares the stores, and is 1 to 64 characters of
A-Z a-z 0-9 . _ -: it goes into response headers, URLs and Redis keys. generateruns on every request, on the request's thread, an event loop included: it never blocks, and should not throw. One that throws costs only its id (PIP-23): a random id names the request or event, the answer is the one CoSec would have given, and the failure is logged at most every ten seconds.- An id is not a secret and need not be unpredictable: a token is signed, and a request id only correlates logs and audit events. The OAuth
stateof social login and the secret of an API key, which must be unpredictable, never come from it: CoSec draws both fromSecureRandomitself.
CoSec's core depends on no id library. For CosId 5, add cosec-cosid. When the application has CosId's CosIdRuntime and no IdGenerator of its own, the starter gives CoSec the ids of the generator cosec.cosid.generator names, CosId's default unless set, as that generator's codec writes them (CosIdIdGenerator). A generator whose ids break the first rule above fails startup. Pick a time-based generator (Snowflake, CosId80) whose clock regression policy fails rather than waits (a wait of zero, CosId's ClockRegressionPolicy.FAIL): CosId's default waits up to a second on the event loop when the clock goes back, and a segment generator waits for its store when its range runs out. CosId does not expose a generator's policy, so CoSec cannot check it; a CosId failure is answered with a random id, logged at most every ten seconds.
implementation("me.ahoo.cosec:cosec-cosid")
implementation("me.ahoo.cosid:cosid-spring-boot-starter") // 5.x, with the cosid.* configuration of your generatorsAny other source of ids is one bean:
@Bean
fun cosecIdGenerator(ids: MyIds): IdGenerator = IdGenerator { ids.next() }Pick a generator that never waits for its store, such as a Snowflake one, since generate runs on the event loop. Without Spring, pass it to Pipeline.builder(…).ids(…) and Pipeline.behindGateway { ids = … } (both experimental), and as the first argument of JwtTokenConverter.
Bridge context
The adapters start each request's coroutine with a context captured on the thread that received it. A BridgeContextContributor adds to that context, so a thread-local your code relies on is restored whenever the pipeline resumes on another thread:
fun interface BridgeContextContributor {
fun capture(): CoroutineContext
}The starter registers MdcContextContributor (the SLF4J MDC) and, with cosec-opentelemetry, the OpenTelemetry context. Every BridgeContextContributor bean is used, in @Order order. capture runs once per request: keep it cheap.
Problem renderer
A host framework that answers its own errors as RFC 9457 problems can answer CoSec's refusals in the same catalog, so its clients meet one (PIP-34). A ProblemRenderer bean renders the body of every refusal: the three adapters' and the served login routes', alike.
fun interface ProblemRenderer {
fun render(problem: Problem): ByteArray
}- What it is given: the
Problemonly: itstype(aProblemType, withstatus,slug,code,uriandtitle), therequestIdtheCoSec-Request-Idheader carries, and thetraceId. Never the decision, the policy that decided, the principal or the request: what a client may learn of a refusal is what CoSec's own body says. - What stays CoSec's: the status and every header:
Content-Type: application/problem+json,CoSec-Request-Id,Retry-AfterandRateLimit-*. The adapter writes them, then the bytesrenderreturns, as they are; a renderer cannot set a status or add a header (WWW-Authenticateincluded, which CoSec does not set). Write anapplication/problem+jsondocument whosestatusisproblem.status. - When it runs: on a refusal only, on the thread that writes the response, an event loop on WebFlux and the gateway. Do not block, and escape every value:
requestIdmay come from the client. - When it fails: a renderer that throws or answers no bytes is replaced by CoSec's own body for that response. The request stays refused, with CoSec's status. Each failure counts in
cosec.problem.render.failedand is logged atWARNat most once a minute (Troubleshooting). - Without one: the body is CoSec's own,
ProblemEncoder's bytes (ProblemRenderer.DEFAULT). The control API's problems are another catalog and are not rendered by it.
Keep CoSec's type and code. CoSec's TypeScript client recognizes a refusal by its type alone (https://cosec.ahoo.me/problems/<slug>) and acts on the slug: it refreshes an expired token, ends the session for a revoked or invalid one, and hands the problem to your callbacks. A renderer that replaces type makes the client blind to those refusals on that host (Clients). Put your catalog's identifiers in extension members beside CoSec's:
@Bean
fun problemRenderer(): ProblemRenderer {
val json = JsonMapper.builder().build()
return ProblemRenderer { problem ->
val code = when (problem.type) {
ProblemType.UNAUTHORIZED, ProblemType.TOKEN_INVALID, ProblemType.TOKEN_EXPIRED,
ProblemType.TOKEN_REVOKED -> "app.auth.unauthenticated"
ProblemType.FORBIDDEN, ProblemType.SCOPE_REJECTED -> "app.auth.forbidden"
else -> "app.error.${problem.type.slug}"
}
json.writeValueAsBytes(
linkedMapOf(
"type" to problem.type.uri, // CoSec's: its clients act on it
"title" to problem.type.title,
"status" to problem.status,
"code" to problem.type.code, // CoSec's
"requestId" to problem.requestId,
"appCode" to code, // your catalog's, as an extension member
),
)
}
}Change listeners
With cosec-control, a ChangeListener receives a ChangeEvent for every step of a change: proposed, checked, shadowed, approved, publishing, published, break-glass requested or approved, and so on. An event never carries document content.
- A
REQUIREDlistener gates publishing and every step of creating break-glass: the step happens only after every REQUIRED listener recorded it withincosec.pipeline.timeout(5 s at the default), otherwise it fails with503and writes nothing. Creating break-glass needs at least one REQUIRED listener. - Other events, and every event to a
BEST_EFFORTlistener, are delivered off the caller; a failure is logged. - Listeners add up: every
ChangeListenerbean is registered next to the starter'sLoggingChangeListener, which backs off only for aLoggingChangeListenerbean of yours.
With cosec-kafka and a KafkaOperations bean, the starter registers KafkaChangeListener under cosec.control.audit.kafka.* (Observability).
Control store
With cosec-control, the control plane keeps revisions, change requests, staging slots, candidates and leases in a ControlStore; the starter's is CoCacheControlStore on Redis. The store, its records (ChangeRequest, RevisionIndex, StageSlot, ...) and the shadow window ports (CandidateStore, ShadowReportSink, ShadowReportReader and their reports, in cosec-spi) are @ExperimentalCoSecApi: the control plane's contract is its HTTP API, and these change with it, so they may change in a minor release. ChangeListener and the ChangeEvent it receives are stable. A store that cannot answer throws ControlStoreException: the control API answers 503 and a maintenance pass does nothing that pass (CTL-52). A value it read that does not decode throws SnapshotFormatException, a 500. It never answers "absent" for either. Besides reading and writing those records by key, a store answers what the maintenance passes visit:
documents(): every document it has indexed revisions for. It may name more than exist, never fewer.openChanges(document)andchanges(state, after, limit, documents): the changes of one document that are not terminal, and a page of the changes in one state, each read now (CTL-54). Every written change that is not terminal is among them; a change whose record does not decode isListedChange.Unreadable, never left out, and maintenance skips its document or its window that pass.openChangesKept()says whether these lists can be trusted; maintenance reclaims nothing until they can, andkeepOpenChanges()makes a new store's lists trusted.eachOpenChange(document, after, visit): whatopenChanges(document)lists, handed tovisitone at a time in the order of their ids, pastafter, untilvisitanswersfalse(DR2-E-4). Each comes as itsid, thesizeits record is stored with, andread, which decodes it (nullwhen it turned out terminal or gone). The control plane weighs each record by its size in the call's work budget before it decodes it, holds the heaviest so far and nothing for a small one, and keeps of each only what it needs, so a document's open changes are never all decoded at once. The default readsopenChangeswhole and knows no size: it passesnull, and each record is then weighed as one at the record cap (18 MB at the defaults, 72 MB of work), which holds a large share of the budget for every proposal. Override it to pass the size, and to read one record at a time, asCoCacheControlStoredoes. A store that delegates to another (ControlStore by inner) and overridesopenChangesoverrides this too, or the delegate answers it.endedChanges(document, endedBefore, limit)andremoveChange(document, id, expected): the changes of a document that ended before a time, the oldest first, and the removal of one ended change's record (CTL-83). AputChangeof a terminal change lists it under itsupdatedAtbefore it writes it, so a write that lost leaves an extra entry, never a missing one; whoever acts on an entry reads its record first.removeChangeremoves the record only while it isexpectedand takes every entry of the change out; withexpectednull, only where there is no record, so an entry whose record is gone leaves. The control plane keeps at mostmax-countended changes a document, on the write that ends one, and reclamation removes those pastmin-agethat published no revision still retained.acquireLease(name, holder, duration)andreleaseLease(name, holder): one instance at a time per task. A release removes the lease only whileholderstill has it, checked and removed in one atomic step (CoCache'sdeleteIfMatch): a lease that expired and another instance took meanwhile stays theirs.withdrawCandidate(key, window): removes a document's candidate only while it is still the one ofwindow, in one atomic step (CTL-26). A change withdraws its candidate once it is terminal, when another may already have staged its own.stagedCandidate(key)andputCandidate(key, expected, candidate): the candidate with the digest a write must name, and a write that lands only over the candidate that was read (null: only if there is none),falsewhen it changed. A stage reads, checks it still holds the document's staging slot, and writes over what it read; a change preempted meanwhile finds its late write refused, and so never replaces the candidate of the change that took the slot (CTL-6). A write whose outcome is unknown is resolved by reading back, never by writing again.ShadowReportReader.readings(window): every instance's report that reads, and inShadowReadings.unreadablethe instances whose report is listed and cannot be read (missing, not decoding, or another instance's). The control plane takes those as missing evidence: the window waits for them and closes insufficient at its longest, naming them (CTL-56). A store that does not answer is still thrown, for the whole call: the window then waits as for any read that failed. The default readsreports(window), which throws for an unreadable report, so a reader that does not overridereadingskeeps such a window open past its longest.ShadowReportSink.write(ResidentDocuments)andShadowReportReader.residents(instances): the documents each instance holds, with the revision of each, as a record of its own beside its status, which stays small (CTL-74,CTL-75). Store it per instance with a life ofShadowReportReader.RESIDENT_TTL(exactly, no jitter: an instance writes it again at half that life).residentsanswers the records of the instances asked that read, and inResidentReadings.unreadablethose whose record is missing or does not decode, whichpropagationcounts asunknown; a record under another instance's key, and a store that does not answer, are thrown. Both are abstract: there is no default, since one that answered "holds nothing" would makeinstalled == holdingclaim that no instance is behind.ShadowReportReader.statusReadings(): the recent statuses that read, and inStatusReadings.unreadablethe instances whose listed status does not decode. The control plane takes those as live and acknowledging no window, so no window passes on them, while it reads every other status andpropagationanswers (CTL-73). A status under another instance's key, and a store that does not answer, are thrown for the whole call. The default readsstatuses(): a reader that does not override it cannot tell a status that does not decode from none, so it fails the read wherestatuses()does, and every window andpropagationwait until that status reads or expires.referrersandputReferrers: each referring document with the revision of it that last indexed the reference, so that a revision's late removal never takes back what a later revision indexed again (CTL-25).RevisionIndex.reclaiming: the records reclamation took out of the index and has not yet seen deleted; a store keeps it with the index, as it keeps the rest of it.
Like the data plane's stores, a read that fails throws: it never answers "absent".
Route maps
By default a request's action is http:<METHOD> and its resource http:path:<path>. A route map gives a service's routes their own actions and typed resources (order:read on order/{orderId}), so policies are written in the service's terms. Mapped requests get the route's action; every other request keeps the http namespace.
{
"service": "order",
"routes": [
{ "method": "GET", "path": "/orders/{orderId}", "action": "order:read", "resource": "order/{orderId}" },
{ "method": "POST", "path": "/orders/{orderId}/cancel", "action": "order:cancel", "resource": "order/{orderId}" }
]
}- The starter loads the route maps listed in
cosec.authorization.routes.location(comma-separated) at startup. A missing or invalid map, a map with no routes, or two routes one request could match, fails startup. Unset, the service loads none, unlessclasspath:cosec-routes.jsonexists: startup then fails until the property names it or is set empty. A gateway host loads none. - With
cosec-openapi, springdoc and Spring Boot Actuator, thecosecServiceGeneratorendpoint generates both documents from the OpenAPI document springdoc scans:routesis the route map to ship ascosec-routes.json,appis the app document (catalog and permission policies) to publish through the control plane.
The file is read strictly: an unknown or missing field fails it (RouteMapCodec.kt).
In code, RouteMapCodec (me.ahoo.cosec.document.route) reads them: load(listOf(location to bytes)) gives the RouteMap the pipeline uses, with the same checks as startup, and decode(bytes, location) one RouteMapDocument. RouteMap.of(routes) builds one from RouteMap.Located routes, and resolve(method, path) answers what the pipeline would give a request: Mapped (the route, its action and resource), Unmapped, or Invalid (a 400). A test of your own route maps loads them so, or through PipelineFixture(routes = …). App documents and catalogs are in Role permissions.
Next: how to propose and land a change, in CONTRIBUTING.md, and the build rules and invariants for changing CoSec, in AGENTS.md.