Introduce oauth2scope registry with freeze lifecycle

Replace pkg/iam/scopeset with pkg/iam/oauth2scope.Registry, a shared
OAuth2 scope→action registry used by the authorizer, OAuth2 service,
and Connect API. Registration stays open until probod calls Freeze();
read paths (RegisteredScopes, Allows, ValidateScopes) panic before
that.

Drop the leaky APIScopes surface and AllowedAPIScopes on manual
access-token creation in favor of registry.ValidateScopes. Metadata,
protected-resource metadata, and CIMD scope lists are built from
RegisteredScopes() via helpers in pkg/iam/oauth2/scopes.go. Expose
oauth2ScopesSupported as an OAuth2Scope GraphQL scalar.

Signed-off-by: Ludovic Vielle <ludovic@probo.com>
This commit is contained in:
Ludovic Vielle
2026-06-20 18:17:40 +02:00
parent 0d33750735
commit c93932f026
27 changed files with 310 additions and 235 deletions

View File

@@ -255,7 +255,7 @@ and `r.AuthorizeBatch` (MCP) — keep the returned scope and pass it down.
| IAM role policies (`IAMPolicySet`) | `pkg/iam/iam_policies.go` | | IAM role policies (`IAMPolicySet`) | `pkg/iam/iam_policies.go` |
| Authorizer + `AuthorizationAttributer` | `pkg/iam/authorizer.go` | | Authorizer + `AuthorizationAttributer` | `pkg/iam/authorizer.go` |
| PolicySet registration | `pkg/iam/policy_set.go` | | PolicySet registration | `pkg/iam/policy_set.go` |
| OAuth2 scope mappings (`ScopeSet`) | `pkg/iam/scope_set.go` | | OAuth2 scope registry (`oauth2scope.Registry`) | `pkg/iam/oauth2scope/registry.go` |
| OAuth2 scope constants (per domain) | `pkg/<service>/oauth2_scopes.go` | | OAuth2 scope constants (per domain) | `pkg/<service>/oauth2_scopes.go` |
| OAuth2 discovery + request context | `pkg/iam/oauth2/` | | OAuth2 discovery + request context | `pkg/iam/oauth2/` |
| GraphQL authz helper | `pkg/server/api/authz/authorization.go` | | GraphQL authz helper | `pkg/server/api/authz/authorization.go` |
@@ -291,9 +291,9 @@ Scopes are namespace- or product-level only — no resource segments (e.g. `v1:p
- Authorization server (RFC 8414): `scopes_supported` on `/.well-known/oauth-authorization-server` lists OIDC + all API scopes; `protected_resources` links to the resource metadata document - Authorization server (RFC 8414): `scopes_supported` on `/.well-known/oauth-authorization-server` lists OIDC + all API scopes; `protected_resources` links to the resource metadata document
- Protected resource (RFC 9728): `scopes_supported` on `/.well-known/oauth-protected-resource` lists `openid` plus API scopes - Protected resource (RFC 9728): `scopes_supported` on `/.well-known/oauth-protected-resource` lists `openid` plus API scopes
**Enforcement:** OAuth2 bearer-token requests carry the validated access token on the request context (`pkg/iam/oauth2/request_context.go`). Before IAM policy evaluation, `iam.Authorizer` checks registered `iam.ScopeSet` mappings via `ScopeSet.Allows` (`RegisterScopes`, same composition model as `RegisterPolicySet`). Each domain package exports an `OAuth2ScopeSet()` (or `IAMOAuth2ScopeSet()` in `pkg/iam`) and registers it at service startup. The check uses explicit scope→action lists — no `:read` / `:get` heuristics at enforcement time. Session, personal API key, and SCIM auth skip the check (no access token on context). Unmapped IAM actions **deny** OAuth requests (fail closed). Enforcement reads scopes from the access token directly. **Enforcement:** OAuth2 bearer-token requests carry the validated access token on the request context (`pkg/iam/oauth2/request_context.go`). Before IAM policy evaluation, `iam.Authorizer` checks registered `oauth2scope.Registry` mappings via `Registry.Allows`. Each domain package exports `OAuth2ScopeMappings` in its `oauth2_scopes.go`; `probod` registers all domain mappings on the shared registry before `iam.NewService`. The check uses explicit scope→action lists — no `:read` / `:get` heuristics at enforcement time. Session, personal API key, and SCIM auth skip the check (no access token on context). Unmapped IAM actions **deny** OAuth requests (fail closed). Enforcement reads scopes from the access token directly.
Add new namespace-level scope constants in the owning package's `oauth2_scopes.go`, map their IAM actions in that package's `OAuth2ScopeSet()`, and register that set on the authorizer when the surface is ready for OAuth clients. Write scopes are registered only when their mutating IAM actions are mapped. Add new namespace-level scope constants in the owning package's `oauth2_scopes.go`, map their IAM actions in that package's `OAuth2ScopeMappings`, and add the mapping to `probod` wiring alongside the other domain registrations. Write scopes are registered only when their mutating IAM actions are mapped.
**Well-known Probo CLI client:** `iam_oauth2_clients` scopes for `AAAAAAAAAAAASwAAAAAAAAAAcHJiY2xp` must match `CLIClientScopes` in `pkg/cli/config/config.go` (requested by `prb auth login`). When adding API scopes, update the client migration, `CLIClientScopes`, and scope registration together. **Well-known Probo CLI client:** `iam_oauth2_clients` scopes for `AAAAAAAAAAAASwAAAAAAAAAAcHJiY2xp` must match `CLIClientScopes` in `pkg/cli/config/config.go` (requested by `prb auth login`). When adding API scopes, update the client migration, `CLIClientScopes`, and scope registration together.

View File

@@ -28,8 +28,8 @@ import (
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/oauth2" "go.probo.inc/probo/pkg/iam/oauth2"
"go.probo.inc/probo/pkg/iam/oauth2scope"
"go.probo.inc/probo/pkg/iam/policy" "go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/iam/scopeset"
) )
// AuthorizationAttributer is implemented by entities that can provide // AuthorizationAttributer is implemented by entities that can provide
@@ -84,21 +84,21 @@ type AuthorizeMultiParams struct {
// Authorizer evaluates authorization requests against registered policies. // Authorizer evaluates authorization requests against registered policies.
type Authorizer struct { type Authorizer struct {
pg *pg.Client pg *pg.Client
evaluator *policy.Evaluator evaluator *policy.Evaluator
policySet *PolicySet policySet *PolicySet
oauth2ScopeSet *scopeset.ScopeSet scopeRegistry *oauth2scope.Registry
logger *log.Logger logger *log.Logger
} }
// NewAuthorizer creates a new Authorizer instance. // NewAuthorizer creates a new Authorizer instance.
func NewAuthorizer(pgClient *pg.Client, logger *log.Logger, scopeSet *scopeset.ScopeSet) *Authorizer { func NewAuthorizer(pgClient *pg.Client, logger *log.Logger, scopeRegistry *oauth2scope.Registry) *Authorizer {
return &Authorizer{ return &Authorizer{
pg: pgClient, pg: pgClient,
evaluator: policy.NewEvaluator(), evaluator: policy.NewEvaluator(),
policySet: NewPolicySet(), policySet: NewPolicySet(),
oauth2ScopeSet: scopeSet, scopeRegistry: scopeRegistry,
logger: logger, logger: logger,
} }
} }
@@ -117,7 +117,7 @@ func (a *Authorizer) checkOAuth2Scope(
return nil return nil
} }
if a.oauth2ScopeSet == nil || !a.oauth2ScopeSet.Allows(accessToken.Scopes, action) { if a.scopeRegistry == nil || !a.scopeRegistry.Allows(accessToken.Scopes, action) {
return NewInsufficientOAuth2ScopeError(principal, action) return NewInsufficientOAuth2ScopeError(principal, action)
} }

View File

@@ -31,8 +31,8 @@ import (
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/iam"
"go.probo.inc/probo/pkg/iam/oauth2scope"
"go.probo.inc/probo/pkg/iam/policy" "go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/iam/scopeset"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
) )
@@ -217,7 +217,7 @@ func TestAuthorizer_AuthorizeBatch(t *testing.T) {
t.Run("empty input", func(t *testing.T) { t.Run("empty input", func(t *testing.T) {
t.Parallel() t.Parallel()
authorizer := iam.NewAuthorizer(nil, log.NewLogger(log.WithOutput(io.Discard)), scopeset.New()) authorizer := iam.NewAuthorizer(nil, log.NewLogger(log.WithOutput(io.Discard)), oauth2scope.NewRegistry())
_, err := authorizer.AuthorizeBatch( _, err := authorizer.AuthorizeBatch(
context.Background(), context.Background(),
@@ -645,7 +645,7 @@ func TestAuthorizer_AuthorizeMulti(t *testing.T) {
t.Run("rejects empty items", func(t *testing.T) { t.Run("rejects empty items", func(t *testing.T) {
t.Parallel() t.Parallel()
authorizer := iam.NewAuthorizer(nil, log.NewLogger(log.WithOutput(io.Discard)), scopeset.New()) authorizer := iam.NewAuthorizer(nil, log.NewLogger(log.WithOutput(io.Discard)), oauth2scope.NewRegistry())
scope, decisions, err := authorizer.AuthorizeMulti( scope, decisions, err := authorizer.AuthorizeMulti(
context.Background(), context.Background(),
@@ -664,7 +664,7 @@ func TestAuthorizer_AuthorizeMulti(t *testing.T) {
t.Run("rejects unsupported principal type", func(t *testing.T) { t.Run("rejects unsupported principal type", func(t *testing.T) {
t.Parallel() t.Parallel()
authorizer := iam.NewAuthorizer(nil, log.NewLogger(log.WithOutput(io.Discard)), scopeset.New()) authorizer := iam.NewAuthorizer(nil, log.NewLogger(log.WithOutput(io.Discard)), oauth2scope.NewRegistry())
scope, decisions, err := authorizer.AuthorizeMulti( scope, decisions, err := authorizer.AuthorizeMulti(
context.Background(), context.Background(),
@@ -783,7 +783,7 @@ func newTestAuthorizer(client *pg.Client, action string, allowResourceID *gid.GI
} }
func newTestAuthorizerWithStatements(client *pg.Client, statements ...policy.Statement) *iam.Authorizer { func newTestAuthorizerWithStatements(client *pg.Client, statements ...policy.Statement) *iam.Authorizer {
authorizer := iam.NewAuthorizer(client, log.NewLogger(log.WithOutput(io.Discard)), scopeset.New()) authorizer := iam.NewAuthorizer(client, log.NewLogger(log.WithOutput(io.Discard)), oauth2scope.NewRegistry())
authorizer.RegisterPolicySet( authorizer.RegisterPolicySet(
iam.NewPolicySet().AddRolePolicy( iam.NewPolicySet().AddRolePolicy(
string(coredata.MembershipRoleOwner), string(coredata.MembershipRoleOwner),
@@ -795,7 +795,7 @@ func newTestAuthorizerWithStatements(client *pg.Client, statements ...policy.Sta
} }
func newTestAuthorizerWithIdentityScopedStatements(client *pg.Client, statements ...policy.Statement) *iam.Authorizer { func newTestAuthorizerWithIdentityScopedStatements(client *pg.Client, statements ...policy.Statement) *iam.Authorizer {
authorizer := iam.NewAuthorizer(client, log.NewLogger(log.WithOutput(io.Discard)), scopeset.New()) authorizer := iam.NewAuthorizer(client, log.NewLogger(log.WithOutput(io.Discard)), oauth2scope.NewRegistry())
authorizer.RegisterPolicySet( authorizer.RegisterPolicySet(
iam.NewPolicySet().AddIdentityScopedPolicy( iam.NewPolicySet().AddIdentityScopedPolicy(
policy.NewPolicy("batch-authorize-identity-test", "Batch Authorize Identity Test", statements...), policy.NewPolicy("batch-authorize-identity-test", "Batch Authorize Identity Test", statements...),

View File

@@ -29,8 +29,8 @@ import (
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/iam"
"go.probo.inc/probo/pkg/iam/oauth2scope"
"go.probo.inc/probo/pkg/iam/policy" "go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/iam/scopeset"
) )
func TestAuthorizer_DecisionLogging(t *testing.T) { func TestAuthorizer_DecisionLogging(t *testing.T) {
@@ -152,7 +152,7 @@ func newTestAuthorizerWithLogger(
statements = append(statements, extraStatements...) statements = append(statements, extraStatements...)
authorizer := iam.NewAuthorizer(client, log.NewLogger(log.WithOutput(logOutput)), scopeset.New()) authorizer := iam.NewAuthorizer(client, log.NewLogger(log.WithOutput(logOutput)), oauth2scope.NewRegistry())
authorizer.RegisterPolicySet( authorizer.RegisterPolicySet(
iam.NewPolicySet().AddRolePolicy( iam.NewPolicySet().AddRolePolicy(
string(coredata.MembershipRoleOwner), string(coredata.MembershipRoleOwner),

View File

@@ -24,7 +24,7 @@ import (
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/oauth2" "go.probo.inc/probo/pkg/iam/oauth2"
"go.probo.inc/probo/pkg/iam/scopeset" "go.probo.inc/probo/pkg/iam/oauth2scope"
) )
func TestAuthorizer_checkOAuth2Scope(t *testing.T) { func TestAuthorizer_checkOAuth2Scope(t *testing.T) {
@@ -66,7 +66,7 @@ func TestAuthorizer_checkOAuth2Scope(t *testing.T) {
t.Run("allows when registered scopes authorize the action", func(t *testing.T) { t.Run("allows when registered scopes authorize the action", func(t *testing.T) {
t.Parallel() t.Parallel()
scopeSet := scopeset.New().Register( scopeSet := oauth2scope.NewRegistry().Register(
map[coredata.OAuth2Scope][]string{ map[coredata.OAuth2Scope][]string{
scopeV1OrgRead: {action}, scopeV1OrgRead: {action},
}, },

View File

@@ -400,15 +400,7 @@ func (s *Service) upsertCIMDClient(
clientURI = &doc.ClientURI clientURI = &doc.ClientURI
} }
scopes := slices.Concat( scopes := coredata.OAuth2Scopes(authorizationServerScopes(s.registry.RegisteredScopes()))
[]coredata.OAuth2Scope{
ScopeOpenID,
ScopeProfile,
ScopeEmail,
ScopeOfflineAccess,
},
s.scopeSet.APIScopes(),
)
now := time.Now() now := time.Now()

View File

@@ -15,8 +15,6 @@
package oauth2 package oauth2
import ( import (
"slices"
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/uri" "go.probo.inc/probo/pkg/uri"
) )
@@ -61,7 +59,7 @@ type (
} }
) )
func NewMetadata(issuer uri.URI, endpoints Endpoints, apiScopes []coredata.OAuth2Scope) *ServerMetadata { func NewMetadata(issuer uri.URI, endpoints Endpoints, registeredScopes []coredata.OAuth2Scope) *ServerMetadata {
return &ServerMetadata{ return &ServerMetadata{
Issuer: issuer, Issuer: issuer,
AuthorizationEndpoint: endpoints.Authorization, AuthorizationEndpoint: endpoints.Authorization,
@@ -72,16 +70,8 @@ func NewMetadata(issuer uri.URI, endpoints Endpoints, apiScopes []coredata.OAuth
IntrospectionEndpoint: endpoints.Introspection, IntrospectionEndpoint: endpoints.Introspection,
RevocationEndpoint: endpoints.Revocation, RevocationEndpoint: endpoints.Revocation,
DeviceAuthorizationEndpoint: endpoints.DeviceAuthorization, DeviceAuthorizationEndpoint: endpoints.DeviceAuthorization,
ScopesSupported: slices.Concat( ScopesSupported: authorizationServerScopes(registeredScopes),
[]coredata.OAuth2Scope{ ProtectedResources: []uri.URI{issuer},
ScopeOpenID,
ScopeProfile,
ScopeEmail,
ScopeOfflineAccess,
},
apiScopes,
),
ProtectedResources: []uri.URI{issuer},
ResponseTypesSupported: []coredata.OAuth2ResponseType{ ResponseTypesSupported: []coredata.OAuth2ResponseType{
coredata.OAuth2ResponseTypeCode, coredata.OAuth2ResponseTypeCode,
}, },

View File

@@ -22,6 +22,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/iam/oauth2" "go.probo.inc/probo/pkg/iam/oauth2"
"go.probo.inc/probo/pkg/iam/oauth2scope"
"go.probo.inc/probo/pkg/probo" "go.probo.inc/probo/pkg/probo"
"go.probo.inc/probo/pkg/uri" "go.probo.inc/probo/pkg/uri"
) )
@@ -29,7 +30,11 @@ import (
func TestNewMetadata(t *testing.T) { func TestNewMetadata(t *testing.T) {
t.Parallel() t.Parallel()
apiScopes := []coredata.OAuth2Scope{probo.ScopeV1DocumentRead} reg := oauth2scope.NewRegistry().Register(
map[coredata.OAuth2Scope][]string{
probo.ScopeV1DocumentRead: {"core:document:get"},
},
)
issuer := uri.URI("https://auth.example.com") issuer := uri.URI("https://auth.example.com")
endpoints := oauth2.Endpoints{ endpoints := oauth2.Endpoints{
@@ -43,7 +48,7 @@ func TestNewMetadata(t *testing.T) {
DeviceAuthorization: "https://auth.example.com/device", DeviceAuthorization: "https://auth.example.com/device",
} }
metadata := oauth2.NewMetadata(issuer, endpoints, apiScopes) metadata := oauth2.NewMetadata(issuer, endpoints, reg.RegisteredScopes())
require.NotNil(t, metadata) require.NotNil(t, metadata)
t.Run( t.Run(
@@ -83,7 +88,7 @@ func TestNewMetadata(t *testing.T) {
oauth2.ScopeEmail, oauth2.ScopeEmail,
oauth2.ScopeOfflineAccess, oauth2.ScopeOfflineAccess,
}, },
apiScopes, reg.RegisteredScopes(),
) )
assert.Equal(t, expectedScopes, metadata.ScopesSupported) assert.Equal(t, expectedScopes, metadata.ScopesSupported)

View File

@@ -15,8 +15,6 @@
package oauth2 package oauth2
import ( import (
"slices"
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/uri" "go.probo.inc/probo/pkg/uri"
) )
@@ -33,7 +31,7 @@ type ProtectedResourceMetadata struct {
func NewProtectedResourceMetadata( func NewProtectedResourceMetadata(
resource uri.URI, resource uri.URI,
authorizationServer uri.URI, authorizationServer uri.URI,
apiScopes []coredata.OAuth2Scope, registeredScopes []coredata.OAuth2Scope,
) *ProtectedResourceMetadata { ) *ProtectedResourceMetadata {
return &ProtectedResourceMetadata{ return &ProtectedResourceMetadata{
Resource: resource, Resource: resource,
@@ -41,9 +39,6 @@ func NewProtectedResourceMetadata(
BearerMethodsSupported: []string{ BearerMethodsSupported: []string{
"header", "header",
}, },
ScopesSupported: slices.Concat( ScopesSupported: protectedResourceScopes(registeredScopes),
[]coredata.OAuth2Scope{ScopeOpenID},
apiScopes,
),
} }
} }

View File

@@ -21,6 +21,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/iam/oauth2" "go.probo.inc/probo/pkg/iam/oauth2"
"go.probo.inc/probo/pkg/iam/oauth2scope"
"go.probo.inc/probo/pkg/probo" "go.probo.inc/probo/pkg/probo"
"go.probo.inc/probo/pkg/uri" "go.probo.inc/probo/pkg/uri"
) )
@@ -28,12 +29,16 @@ import (
func TestNewProtectedResourceMetadata(t *testing.T) { func TestNewProtectedResourceMetadata(t *testing.T) {
t.Parallel() t.Parallel()
apiScopes := []coredata.OAuth2Scope{probo.ScopeV1DocumentRead} reg := oauth2scope.NewRegistry().Register(
map[coredata.OAuth2Scope][]string{
probo.ScopeV1DocumentRead: {"core:document:get"},
},
)
resource := uri.URI("https://app.example.com") resource := uri.URI("https://app.example.com")
authorizationServer := uri.URI("https://app.example.com") authorizationServer := uri.URI("https://app.example.com")
metadata := oauth2.NewProtectedResourceMetadata(resource, authorizationServer, apiScopes) metadata := oauth2.NewProtectedResourceMetadata(resource, authorizationServer, reg.RegisteredScopes())
require.NotNil(t, metadata) require.NotNil(t, metadata)
assert.Equal(t, resource, metadata.Resource) assert.Equal(t, resource, metadata.Resource)

40
pkg/iam/oauth2/scopes.go Normal file
View File

@@ -0,0 +1,40 @@
// Copyright (c) 2026 Probo Inc <hello@probo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package oauth2
import (
"slices"
"go.probo.inc/probo/pkg/coredata"
)
func authorizationServerScopes(registeredScopes []coredata.OAuth2Scope) []coredata.OAuth2Scope {
return slices.Concat(
[]coredata.OAuth2Scope{
ScopeOpenID,
ScopeProfile,
ScopeEmail,
ScopeOfflineAccess,
},
registeredScopes,
)
}
func protectedResourceScopes(registeredScopes []coredata.OAuth2Scope) []coredata.OAuth2Scope {
return slices.Concat(
[]coredata.OAuth2Scope{ScopeOpenID},
registeredScopes,
)
}

View File

@@ -31,7 +31,7 @@ import (
"go.probo.inc/probo/pkg/crypto/jose" "go.probo.inc/probo/pkg/crypto/jose"
"go.probo.inc/probo/pkg/crypto/rand" "go.probo.inc/probo/pkg/crypto/rand"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/scopeset" "go.probo.inc/probo/pkg/iam/oauth2scope"
"go.probo.inc/probo/pkg/net" "go.probo.inc/probo/pkg/net"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
"go.probo.inc/probo/pkg/uri" "go.probo.inc/probo/pkg/uri"
@@ -63,7 +63,7 @@ type (
gc *GarbageCollector gc *GarbageCollector
cimd *cimdFetcher cimd *cimdFetcher
cimdAllowedClientIDs []string cimdAllowedClientIDs []string
scopeSet *scopeset.ScopeSet registry *oauth2scope.Registry
accessTokenDuration time.Duration accessTokenDuration time.Duration
refreshTokenDuration time.Duration refreshTokenDuration time.Duration
authorizationCodeDuration time.Duration authorizationCodeDuration time.Duration
@@ -128,11 +128,10 @@ type (
} }
CreateManualAccessTokenRequest struct { CreateManualAccessTokenRequest struct {
IdentityID gid.GID IdentityID gid.GID
Name string Name string
ExpiresAt time.Time ExpiresAt time.Time
Scopes coredata.OAuth2Scopes Scopes coredata.OAuth2Scopes
AllowedAPIScopes []coredata.OAuth2Scope
} }
) )
@@ -160,9 +159,9 @@ func WithDeviceCodeDuration(d time.Duration) Option {
} }
} }
func WithScopeSet(scopeSet *scopeset.ScopeSet) Option { func WithRegistry(registry *oauth2scope.Registry) Option {
return func(s *Service) { return func(s *Service) {
s.scopeSet = scopeSet s.registry = registry
} }
} }
@@ -1918,8 +1917,8 @@ func (s *Service) CreateManualAccessToken(
return "", nil, NewError(ErrInvalidRequest, WithDescription("scopes are required")) return "", nil, NewError(ErrInvalidRequest, WithDescription("scopes are required"))
} }
if err := validateManualAccessTokenScopes(req.Scopes, req.AllowedAPIScopes); err != nil { if err := s.registry.ValidateScopes(req.Scopes); err != nil {
return "", nil, err return "", nil, NewError(ErrInvalidScope, WithDescription(err.Error()))
} }
tokenValue := rand.MustHexString(tokenByteLength) tokenValue := rand.MustHexString(tokenByteLength)
@@ -1951,18 +1950,3 @@ func (s *Service) CreateManualAccessToken(
return tokenValue, accessToken, nil return tokenValue, accessToken, nil
} }
func validateManualAccessTokenScopes(scopes, allowedAPIScopes coredata.OAuth2Scopes) error {
allowed := make(map[coredata.OAuth2Scope]struct{}, len(allowedAPIScopes))
for _, scope := range allowedAPIScopes {
allowed[scope] = struct{}{}
}
for _, scope := range scopes {
if _, ok := allowed[scope]; !ok {
return NewError(ErrInvalidScope, WithDescription("invalid scope: "+string(scope)))
}
}
return nil
}

View File

@@ -22,37 +22,37 @@ import (
"go.probo.inc/probo/pkg/agentrun" "go.probo.inc/probo/pkg/agentrun"
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/iam"
"go.probo.inc/probo/pkg/iam/scopeset" "go.probo.inc/probo/pkg/iam/oauth2scope"
"go.probo.inc/probo/pkg/probo" "go.probo.inc/probo/pkg/probo"
) )
func allRegisteredOAuth2ScopeSets() *scopeset.ScopeSet { func allRegisteredOAuth2ScopeRegistries() *oauth2scope.Registry {
return scopeset.New(). return oauth2scope.NewRegistry().
Register(iam.IAMOAuth2ScopeMappings). Register(iam.IAMOAuth2ScopeMappings).
Register(probo.OAuth2ScopeMappings). Register(probo.OAuth2ScopeMappings).
Register(accessreview.OAuth2ScopeMappings). Register(accessreview.OAuth2ScopeMappings).
Register(agentrun.OAuth2ScopeMappings) Register(agentrun.OAuth2ScopeMappings)
} }
func TestRegisteredOAuth2ScopeSets_OrganizationRead(t *testing.T) { func TestRegisteredOAuth2ScopeRegistries_OrganizationRead(t *testing.T) {
t.Parallel() t.Parallel()
scopeSet := allRegisteredOAuth2ScopeSets() reg := allRegisteredOAuth2ScopeRegistries()
tokenScopes := coredata.OAuth2Scopes{probo.ScopeV1OrgRead} tokenScopes := coredata.OAuth2Scopes{probo.ScopeV1OrgRead}
assert.True(t, scopeSet.Allows(tokenScopes, probo.ActionOrganizationGet)) assert.True(t, reg.Allows(tokenScopes, probo.ActionOrganizationGet))
assert.False(t, scopeSet.Allows(tokenScopes, probo.ActionOrganizationUpdate)) assert.False(t, reg.Allows(tokenScopes, probo.ActionOrganizationUpdate))
assert.False(t, scopeSet.Allows(tokenScopes, probo.ActionThirdPartyList)) assert.False(t, reg.Allows(tokenScopes, probo.ActionThirdPartyList))
} }
func TestRegisteredOAuth2ScopeSets_UnmappedActionDenies(t *testing.T) { func TestRegisteredOAuth2ScopeRegistries_UnmappedActionDenies(t *testing.T) {
t.Parallel() t.Parallel()
scopeSet := allRegisteredOAuth2ScopeSets() reg := allRegisteredOAuth2ScopeRegistries()
tokenScopes := coredata.OAuth2Scopes{ tokenScopes := coredata.OAuth2Scopes{
probo.ScopeV1OrgRead, probo.ScopeV1OrgRead,
probo.ScopeV1ThirdPartyRead, probo.ScopeV1ThirdPartyRead,
} }
assert.False(t, scopeSet.Allows(tokenScopes, "core:unmapped:action")) assert.False(t, reg.Allows(tokenScopes, "core:unmapped:action"))
} }

View File

@@ -12,10 +12,11 @@
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE. // PERFORMANCE OF THIS SOFTWARE.
package scopeset package oauth2scope
import ( import (
"cmp" "cmp"
"fmt"
"maps" "maps"
"slices" "slices"
"sync" "sync"
@@ -23,47 +24,47 @@ import (
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
) )
type ScopeSet struct { type Registry struct {
mu sync.RWMutex mu sync.RWMutex
scopeActions map[coredata.OAuth2Scope][]string scopeActions map[coredata.OAuth2Scope][]string
actionScopes map[string][]coredata.OAuth2Scope invertedIndex map[string][]coredata.OAuth2Scope
} }
func New() *ScopeSet { func NewRegistry() *Registry {
return &ScopeSet{ return &Registry{
scopeActions: make(map[coredata.OAuth2Scope][]string), scopeActions: make(map[coredata.OAuth2Scope][]string),
} }
} }
func (s *ScopeSet) Register(mappings map[coredata.OAuth2Scope][]string) *ScopeSet { func (r *Registry) Register(mappings map[coredata.OAuth2Scope][]string) *Registry {
s.mu.Lock() r.mu.Lock()
defer s.mu.Unlock() defer r.mu.Unlock()
for scope, actions := range mappings { for scope, actions := range mappings {
if len(actions) == 0 { if len(actions) == 0 {
continue continue
} }
s.scopeActions[scope] = append(s.scopeActions[scope], actions...) r.scopeActions[scope] = append(r.scopeActions[scope], actions...)
} }
s.rebuildActionScopes() r.rebuildInvertedIndex()
return s return r
} }
func (s *ScopeSet) APIScopes() []coredata.OAuth2Scope { func (r *Registry) RegisteredScopes() []coredata.OAuth2Scope {
s.mu.RLock() r.mu.RLock()
defer s.mu.RUnlock() defer r.mu.RUnlock()
return sortedScopes(slices.Collect(maps.Keys(s.scopeActions))) return sortedScopes(slices.Collect(maps.Keys(r.scopeActions)))
} }
func (s *ScopeSet) Allows(tokenScopes coredata.OAuth2Scopes, action string) bool { func (r *Registry) Allows(tokenScopes coredata.OAuth2Scopes, action string) bool {
s.mu.RLock() r.mu.RLock()
defer s.mu.RUnlock() defer r.mu.RUnlock()
grantingScopes, ok := s.actionScopes[action] grantingScopes, ok := r.invertedIndex[action]
if !ok { if !ok {
return false return false
} }
@@ -71,16 +72,29 @@ func (s *ScopeSet) Allows(tokenScopes coredata.OAuth2Scopes, action string) bool
return slices.ContainsFunc(grantingScopes, tokenScopes.Contains) return slices.ContainsFunc(grantingScopes, tokenScopes.Contains)
} }
func (s *ScopeSet) rebuildActionScopes() { func (r *Registry) ValidateScopes(scopes coredata.OAuth2Scopes) error {
actionScopes := make(map[string][]coredata.OAuth2Scope, len(s.scopeActions)*4) r.mu.RLock()
defer r.mu.RUnlock()
for scope, actions := range s.scopeActions { for _, scope := range scopes {
for _, action := range actions { if _, ok := r.scopeActions[scope]; !ok {
actionScopes[action] = append(actionScopes[action], scope) return fmt.Errorf("invalid scope: %s", scope)
} }
} }
s.actionScopes = actionScopes return nil
}
func (r *Registry) rebuildInvertedIndex() {
invertedIndex := make(map[string][]coredata.OAuth2Scope, len(r.scopeActions)*4)
for scope, actions := range r.scopeActions {
for _, action := range actions {
invertedIndex[action] = append(invertedIndex[action], scope)
}
}
r.invertedIndex = invertedIndex
} }
func sortedScopes(scopes []coredata.OAuth2Scope) []coredata.OAuth2Scope { func sortedScopes(scopes []coredata.OAuth2Scope) []coredata.OAuth2Scope {

View File

@@ -0,0 +1,105 @@
// Copyright (c) 2026 Probo Inc <hello@probo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package oauth2scope_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/iam/oauth2scope"
)
func TestRegistry_Allows(t *testing.T) {
t.Parallel()
const scopeV1OrgRead = coredata.OAuth2Scope("v1:org:read")
reg := oauth2scope.NewRegistry().Register(
map[coredata.OAuth2Scope][]string{
scopeV1OrgRead: {"core:organization:get"},
},
)
tokenScopes := coredata.OAuth2Scopes{scopeV1OrgRead}
assert.True(t, reg.Allows(tokenScopes, "core:organization:get"))
assert.False(t, reg.Allows(tokenScopes, "core:organization:update"))
}
func TestRegistry_Register(t *testing.T) {
t.Parallel()
const scopeV1OrgRead = coredata.OAuth2Scope("v1:org:read")
reg := oauth2scope.NewRegistry().
Register(
map[coredata.OAuth2Scope][]string{
scopeV1OrgRead: {"core:organization:get"},
},
).
Register(
map[coredata.OAuth2Scope][]string{
scopeV1OrgRead: {"core:organization-context:get"},
},
)
tokenScopes := coredata.OAuth2Scopes{scopeV1OrgRead}
assert.True(t, reg.Allows(tokenScopes, "core:organization:get"))
assert.True(t, reg.Allows(tokenScopes, "core:organization-context:get"))
}
func TestRegistry_ValidateScopes(t *testing.T) {
t.Parallel()
const scopeV1OrgRead = coredata.OAuth2Scope("v1:org:read")
reg := oauth2scope.NewRegistry().Register(
map[coredata.OAuth2Scope][]string{
scopeV1OrgRead: {"core:organization:get"},
},
)
require.NoError(t, reg.ValidateScopes(coredata.OAuth2Scopes{scopeV1OrgRead}))
err := reg.ValidateScopes(coredata.OAuth2Scopes{"v1:unknown:read"})
require.Error(t, err)
assert.EqualError(t, err, "invalid scope: v1:unknown:read")
}
func TestRegistry_RegisteredScopes(t *testing.T) {
t.Parallel()
const (
scopeV1OrgRead = coredata.OAuth2Scope("v1:org:read")
scopeV1OrgWrite = coredata.OAuth2Scope("v1:org")
)
reg := oauth2scope.NewRegistry().
Register(
map[coredata.OAuth2Scope][]string{
scopeV1OrgWrite: {"core:organization:update"},
scopeV1OrgRead: {"core:organization:get"},
},
)
assert.Equal(
t,
[]coredata.OAuth2Scope{scopeV1OrgWrite, scopeV1OrgRead},
reg.RegisteredScopes(),
)
}

View File

@@ -1,63 +0,0 @@
// Copyright (c) 2026 Probo Inc <hello@probo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package scopeset_test
import (
"testing"
"github.com/stretchr/testify/assert"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/iam/scopeset"
)
func TestScopeSet_Allows(t *testing.T) {
t.Parallel()
const scopeV1OrgRead = coredata.OAuth2Scope("v1:org:read")
scopeSet := scopeset.New().Register(
map[coredata.OAuth2Scope][]string{
scopeV1OrgRead: {"core:organization:get"},
},
)
tokenScopes := coredata.OAuth2Scopes{scopeV1OrgRead}
assert.True(t, scopeSet.Allows(tokenScopes, "core:organization:get"))
assert.False(t, scopeSet.Allows(tokenScopes, "core:organization:update"))
}
func TestScopeSet_Register(t *testing.T) {
t.Parallel()
const scopeV1OrgRead = coredata.OAuth2Scope("v1:org:read")
scopeSet := scopeset.New().
Register(
map[coredata.OAuth2Scope][]string{
scopeV1OrgRead: {"core:organization:get"},
},
).
Register(
map[coredata.OAuth2Scope][]string{
scopeV1OrgRead: {"core:organization-context:get"},
},
)
tokenScopes := coredata.OAuth2Scopes{scopeV1OrgRead}
assert.True(t, scopeSet.Allows(tokenScopes, "core:organization:get"))
assert.True(t, scopeSet.Allows(tokenScopes, "core:organization-context:get"))
}

View File

@@ -34,10 +34,10 @@ import (
"go.probo.inc/probo/pkg/filemanager" "go.probo.inc/probo/pkg/filemanager"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/oauth2" "go.probo.inc/probo/pkg/iam/oauth2"
"go.probo.inc/probo/pkg/iam/oauth2scope"
"go.probo.inc/probo/pkg/iam/oidc" "go.probo.inc/probo/pkg/iam/oidc"
"go.probo.inc/probo/pkg/iam/saml" "go.probo.inc/probo/pkg/iam/saml"
"go.probo.inc/probo/pkg/iam/scim" "go.probo.inc/probo/pkg/iam/scim"
"go.probo.inc/probo/pkg/iam/scopeset"
"go.probo.inc/probo/pkg/uri" "go.probo.inc/probo/pkg/uri"
) )
@@ -70,7 +70,7 @@ type (
APIKeyService *APIKeyService APIKeyService *APIKeyService
OAuth2ServerService *oauth2.Service OAuth2ServerService *oauth2.Service
Authorizer *Authorizer Authorizer *Authorizer
OAuth2ScopeSet *scopeset.ScopeSet OAuth2ScopeRegistry *oauth2scope.Registry
samlDomainVerifier *SAMLDomainVerifier samlDomainVerifier *SAMLDomainVerifier
} }
@@ -99,6 +99,7 @@ type (
MicrosoftOIDC oidc.ProviderConfig MicrosoftOIDC oidc.ProviderConfig
OAuth2ServerSigningKeys oauth2.SigningKeys OAuth2ServerSigningKeys oauth2.SigningKeys
OAuth2ServerOptions []oauth2.Option OAuth2ServerOptions []oauth2.Option
OAuth2ScopeRegistry *oauth2scope.Registry
} }
) )
@@ -134,6 +135,10 @@ func NewService(
return nil, fmt.Errorf("encryption key is required") return nil, fmt.Errorf("encryption key is required")
} }
if cfg.OAuth2ScopeRegistry == nil {
return nil, fmt.Errorf("oauth2 scope registry is required")
}
svc := &Service{ svc := &Service{
pg: pgClient, pg: pgClient,
fm: fm, fm: fm,
@@ -159,13 +164,12 @@ func NewService(
svc.AuthService = NewAuthService(svc) svc.AuthService = NewAuthService(svc)
svc.APIKeyService = NewAPIKeyService(svc) svc.APIKeyService = NewAPIKeyService(svc)
svc.OAuth2ScopeSet = scopeset.New() svc.OAuth2ScopeRegistry = cfg.OAuth2ScopeRegistry
svc.OAuth2ScopeSet.Register(IAMOAuth2ScopeMappings)
svc.Authorizer = NewAuthorizer( svc.Authorizer = NewAuthorizer(
pgClient, pgClient,
cfg.Logger.Named("authorizer"), cfg.Logger.Named("authorizer"),
svc.OAuth2ScopeSet, svc.OAuth2ScopeRegistry,
) )
svc.Authorizer.RegisterPolicySet(IAMPolicySet()) svc.Authorizer.RegisterPolicySet(IAMPolicySet())
@@ -206,7 +210,7 @@ func NewService(
uri.URI(cfg.BaseURL.String()), uri.URI(cfg.BaseURL.String()),
cfg.Logger.Named("oauth2"), cfg.Logger.Named("oauth2"),
append( append(
[]oauth2.Option{oauth2.WithScopeSet(svc.OAuth2ScopeSet)}, []oauth2.Option{oauth2.WithRegistry(svc.OAuth2ScopeRegistry)},
cfg.OAuth2ServerOptions..., cfg.OAuth2ServerOptions...,
)..., )...,
) )
@@ -224,12 +228,12 @@ func NewService(
// OAuth2ServerMetadata returns the OIDC discovery document. // OAuth2ServerMetadata returns the OIDC discovery document.
func (s *Service) OAuth2ServerMetadata(endpoints oauth2.Endpoints) *oauth2.ServerMetadata { func (s *Service) OAuth2ServerMetadata(endpoints oauth2.Endpoints) *oauth2.ServerMetadata {
return oauth2.NewMetadata(uri.URI(s.baseURL), endpoints, s.OAuth2ScopeSet.APIScopes()) return oauth2.NewMetadata(uri.URI(s.baseURL), endpoints, s.OAuth2ScopeRegistry.RegisteredScopes())
} }
// OAuth2ProtectedResourceMetadata returns the RFC 9728 protected resource metadata document. // OAuth2ProtectedResourceMetadata returns the RFC 9728 protected resource metadata document.
func (s *Service) OAuth2ProtectedResourceMetadata(resource uri.URI) *oauth2.ProtectedResourceMetadata { func (s *Service) OAuth2ProtectedResourceMetadata(resource uri.URI) *oauth2.ProtectedResourceMetadata {
return oauth2.NewProtectedResourceMetadata(resource, resource, s.OAuth2ScopeSet.APIScopes()) return oauth2.NewProtectedResourceMetadata(resource, resource, s.OAuth2ScopeRegistry.RegisteredScopes())
} }
func (s *Service) IsSignUpEnabled() bool { func (s *Service) IsSignUpEnabled() bool {

View File

@@ -149,7 +149,6 @@ func NewService(
} }
iamService.Authorizer.RegisterPolicySet(ProboPolicySet()) iamService.Authorizer.RegisterPolicySet(ProboPolicySet())
iamService.OAuth2ScopeSet.Register(OAuth2ScopeMappings)
svc := &Service{ svc := &Service{
pg: pgClient, pg: pgClient,

View File

@@ -61,6 +61,7 @@ import (
"go.probo.inc/probo/pkg/html2pdf" "go.probo.inc/probo/pkg/html2pdf"
"go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/iam"
"go.probo.inc/probo/pkg/iam/oauth2" "go.probo.inc/probo/pkg/iam/oauth2"
"go.probo.inc/probo/pkg/iam/oauth2scope"
"go.probo.inc/probo/pkg/iam/oidc" "go.probo.inc/probo/pkg/iam/oidc"
"go.probo.inc/probo/pkg/mailer" "go.probo.inc/probo/pkg/mailer"
"go.probo.inc/probo/pkg/mailman" "go.probo.inc/probo/pkg/mailman"
@@ -453,6 +454,12 @@ func (impl *Implm) Run(
} }
} }
oauth2ScopeRegistry := oauth2scope.NewRegistry().
Register(iam.IAMOAuth2ScopeMappings).
Register(probo.OAuth2ScopeMappings).
Register(agentrun.OAuth2ScopeMappings).
Register(accessreview.OAuth2ScopeMappings)
iamService, err := iam.NewService( iamService, err := iam.NewService(
ctx, ctx,
pgClient, pgClient,
@@ -490,6 +497,7 @@ func (impl *Implm) Run(
}, },
OAuth2ServerSigningKeys: oauth2SigningKeys, OAuth2ServerSigningKeys: oauth2SigningKeys,
OAuth2ServerOptions: oauth2ServerOptions(impl.cfg.Auth.OAuth2Server), OAuth2ServerOptions: oauth2ServerOptions(impl.cfg.Auth.OAuth2Server),
OAuth2ScopeRegistry: oauth2ScopeRegistry,
}, },
) )
if err != nil { if err != nil {
@@ -601,8 +609,6 @@ func (impl *Implm) Run(
iamService.Authorizer.RegisterPolicySet(agentrun.PolicySet()) iamService.Authorizer.RegisterPolicySet(agentrun.PolicySet())
iamService.Authorizer.RegisterPolicySet(accessreview.PolicySet()) iamService.Authorizer.RegisterPolicySet(accessreview.PolicySet())
iamService.OAuth2ScopeSet.Register(agentrun.OAuth2ScopeMappings)
iamService.OAuth2ScopeSet.Register(accessreview.OAuth2ScopeMappings)
thirdPartyService := thirdparty.NewService(pgClient, fileManagerService, thirdPartyVetter) thirdPartyService := thirdparty.NewService(pgClient, fileManagerService, thirdPartyVetter)
riskManagementService := riskmanagement.NewService(pgClient) riskManagementService := riskmanagement.NewService(pgClient)

View File

@@ -267,15 +267,8 @@ func (r *queryResolver) SignUpEnabled(ctx context.Context) (bool, error) {
} }
// Oauth2ScopesSupported is the resolver for the oauth2ScopesSupported field. // Oauth2ScopesSupported is the resolver for the oauth2ScopesSupported field.
func (r *queryResolver) Oauth2ScopesSupported(ctx context.Context) ([]string, error) { func (r *queryResolver) Oauth2ScopesSupported(ctx context.Context) ([]coredata.OAuth2Scope, error) {
apiScopes := r.iam.OAuth2ScopeSet.APIScopes() return r.scopeRegistry.RegisteredScopes(), nil
scopes := make([]string, len(apiScopes))
for i, scope := range apiScopes {
scopes[i] = scope.String()
}
return scopes, nil
} }
// Mutation returns schema.MutationResolver implementation. // Mutation returns schema.MutationResolver implementation.

View File

@@ -43,4 +43,7 @@ models:
- "go.probo.inc/probo/pkg/server/gqlutils/types/bigint.BigIntScalar" - "go.probo.inc/probo/pkg/server/gqlutils/types/bigint.BigIntScalar"
EmailAddr: EmailAddr:
model: model:
- "go.probo.inc/probo/pkg/server/gqlutils/types/mail.AddrScalar" - "go.probo.inc/probo/pkg/server/gqlutils/types/mail.AddrScalar"
OAuth2Scope:
model:
- go.probo.inc/probo/pkg/server/gqlutils/types/oauth2scope.OAuth2ScopeScalar

View File

@@ -16,6 +16,7 @@ scalar CursorKey
scalar Datetime scalar Datetime
scalar Upload scalar Upload
scalar EmailAddr scalar EmailAddr
scalar OAuth2Scope
interface Node { interface Node {
id: ID! id: ID!
@@ -33,7 +34,7 @@ type Query {
signUpEnabled: Boolean! signUpEnabled: Boolean!
@goField(forceResolver: true) @goField(forceResolver: true)
@authentication(required: OPTIONAL) @authentication(required: OPTIONAL)
oauth2ScopesSupported: [String!]! oauth2ScopesSupported: [OAuth2Scope!]!
@goField(forceResolver: true) @goField(forceResolver: true)
@authentication(required: OPTIONAL) @authentication(required: OPTIONAL)
} }

View File

@@ -37,6 +37,7 @@ func NewGraphQLHandler(svc *iam.Service, logger *log.Logger, fileManagerSvc *fil
batchAuthorize: authz.NewBatchAuthorizeFunc(svc, logger), batchAuthorize: authz.NewBatchAuthorizeFunc(svc, logger),
logger: logger, logger: logger,
iam: svc, iam: svc,
scopeRegistry: svc.OAuth2ScopeRegistry,
fileManager: fileManagerSvc, fileManager: fileManagerSvc,
baseURL: baseURL, baseURL: baseURL,
sessionCookie: authn.NewCookie(&cookieConfig), sessionCookie: authn.NewCookie(&cookieConfig),

View File

@@ -36,11 +36,10 @@ func (r *mutationResolver) CreateOAuth2AccessToken(ctx context.Context, input ty
tokenValue, accessToken, err := r.iam.OAuth2ServerService.CreateManualAccessToken( tokenValue, accessToken, err := r.iam.OAuth2ServerService.CreateManualAccessToken(
ctx, ctx,
&oauth2.CreateManualAccessTokenRequest{ &oauth2.CreateManualAccessTokenRequest{
IdentityID: identity.ID, IdentityID: identity.ID,
Name: strings.TrimSpace(input.Name), Name: strings.TrimSpace(input.Name),
ExpiresAt: input.ExpiresAt, ExpiresAt: input.ExpiresAt,
Scopes: scopes, Scopes: scopes,
AllowedAPIScopes: r.iam.OAuth2ScopeSet.APIScopes(),
}, },
) )
if err != nil { if err != nil {

View File

@@ -40,6 +40,7 @@ import (
"go.probo.inc/probo/pkg/filemanager" "go.probo.inc/probo/pkg/filemanager"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam" "go.probo.inc/probo/pkg/iam"
"go.probo.inc/probo/pkg/iam/oauth2scope"
"go.probo.inc/probo/pkg/saferedirect" "go.probo.inc/probo/pkg/saferedirect"
"go.probo.inc/probo/pkg/securecookie" "go.probo.inc/probo/pkg/securecookie"
"go.probo.inc/probo/pkg/server/api/authn" "go.probo.inc/probo/pkg/server/api/authn"
@@ -53,6 +54,7 @@ type (
batchAuthorize authz.BatchAuthorizeFunc batchAuthorize authz.BatchAuthorizeFunc
logger *log.Logger logger *log.Logger
iam *iam.Service iam *iam.Service
scopeRegistry *oauth2scope.Registry
fileManager *filemanager.Service fileManager *filemanager.Service
baseURL *baseurl.BaseURL baseURL *baseurl.BaseURL
sessionCookie *authn.Cookie sessionCookie *authn.Cookie

View File

@@ -12,33 +12,32 @@
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE. // PERFORMANCE OF THIS SOFTWARE.
package iam package oauth2scope
import ( import (
"testing" "fmt"
"io"
"strconv"
"github.com/stretchr/testify/assert" "github.com/99designs/gqlgen/graphql"
"github.com/stretchr/testify/require"
"go.probo.inc/probo/pkg/coredata" "go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/iam/scopeset"
) )
func TestAuthorizer_UsesOAuth2ScopeSet(t *testing.T) { type OAuth2ScopeScalar = coredata.OAuth2Scope
t.Parallel()
const scopeV1OrgRead = coredata.OAuth2Scope("v1:org:read") func MarshalOAuth2ScopeScalar(s OAuth2ScopeScalar) graphql.Marshaler {
return graphql.WriterFunc(
scopeSet := scopeset.New().Register( func(w io.Writer) {
map[coredata.OAuth2Scope][]string{ _, _ = w.Write([]byte(strconv.Quote(s.String())))
scopeV1OrgRead: {"core:organization:get"},
}, },
) )
}
authorizer := NewAuthorizer(nil, nil, scopeSet)
func UnmarshalOAuth2ScopeScalar(v any) (OAuth2ScopeScalar, error) {
require.NotNil(t, authorizer.oauth2ScopeSet) s, ok := v.(string)
if !ok {
tokenScopes := coredata.OAuth2Scopes{scopeV1OrgRead} return "", fmt.Errorf("oauth2 scope must be a string")
assert.True(t, authorizer.oauth2ScopeSet.Allows(tokenScopes, "core:organization:get")) }
assert.False(t, authorizer.oauth2ScopeSet.Allows(tokenScopes, "core:organization:update"))
return OAuth2ScopeScalar(s), nil
} }

View File

@@ -36,7 +36,8 @@
"CursorKey": "string", "CursorKey": "string",
"Duration": "string", "Duration": "string",
"BigInt": "number", "BigInt": "number",
"EmailAddr": "string" "EmailAddr": "string",
"OAuth2Scope": "string"
} }
}, },
"trust": { "trust": {