@apso/cli 0.47.6 → 0.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -1
- package/dist/commands/dev.d.ts +2 -0
- package/dist/commands/dev.js +20 -3
- package/dist/commands/generate.js +55 -13
- package/dist/commands/mcp/serve.js +24 -41
- package/dist/commands/schema/diff.js +3 -4
- package/dist/commands/schema/pull.js +13 -11
- package/dist/commands/schema/push.js +6 -5
- package/dist/commands/schema/validate.d.ts +10 -0
- package/dist/commands/schema/validate.js +54 -0
- package/dist/commands/test/access.d.ts +11 -0
- package/dist/commands/test/access.js +65 -0
- package/dist/lib/access/cases.d.ts +120 -0
- package/dist/lib/access/cases.js +1163 -0
- package/dist/lib/access/index.d.ts +4 -0
- package/dist/lib/access/index.js +7 -0
- package/dist/lib/access/report.d.ts +75 -0
- package/dist/lib/access/report.js +118 -0
- package/dist/lib/access/rules.json +207 -0
- package/dist/lib/access/run.d.ts +38 -0
- package/dist/lib/access/run.js +111 -0
- package/dist/lib/access/tokens.d.ts +46 -0
- package/dist/lib/access/tokens.js +139 -0
- package/dist/lib/api/services.d.ts +10 -7
- package/dist/lib/api/services.js +19 -32
- package/dist/lib/apsorc-parser.d.ts +1 -1
- package/dist/lib/apsorc-parser.js +2 -0
- package/dist/lib/ddl/change.js +2 -0
- package/dist/lib/ddl/index.d.ts +11 -1
- package/dist/lib/ddl/index.js +30 -16
- package/dist/lib/ddl/sync.d.ts +25 -0
- package/dist/lib/ddl/sync.js +78 -0
- package/dist/lib/deploy/server-push.js +3 -1
- package/dist/lib/generators/go.d.ts +25 -7
- package/dist/lib/generators/go.js +365 -128
- package/dist/lib/generators/python.d.ts +9 -3
- package/dist/lib/generators/python.js +282 -47
- package/dist/lib/generators/typescript.d.ts +3 -5
- package/dist/lib/generators/typescript.js +78 -64
- package/dist/lib/guards.d.ts +111 -13
- package/dist/lib/guards.js +287 -23
- package/dist/lib/templates/entities/entity-col-array.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-array.eta +2 -2
- package/dist/lib/templates/go/dto/dto-col-date.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-decimal.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-enum.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-float.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-integer.eta +3 -3
- package/dist/lib/templates/go/dto/dto-col-numeric.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-string.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-text.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-timestamp.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-timestamptz.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-uuid.eta +1 -1
- package/dist/lib/templates/go/dto/dto-col-varchar.eta +1 -1
- package/dist/lib/templates/go/dto/dto.eta +17 -18
- package/dist/lib/templates/go/handlers/handler.eta +10 -8
- package/dist/lib/templates/go/handlers/scope.eta +3 -2
- package/dist/lib/templates/go/index-module.eta +10 -5
- package/dist/lib/templates/go/mcp.eta +307 -0
- package/dist/lib/templates/go/middleware/auth.eta +587 -166
- package/dist/lib/templates/go/middleware/permission.eta +174 -0
- package/dist/lib/templates/go/models/model.eta +22 -19
- package/dist/lib/templates/go/models/schema.eta +72 -0
- package/dist/lib/templates/go/services/service.eta +84 -35
- package/dist/lib/templates/go/utils/query.eta +68 -7
- package/dist/lib/templates/guards/guards.module.eta +37 -29
- package/dist/lib/templates/guards/index.eta +4 -0
- package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
- package/dist/lib/templates/guards/key.guard.eta +280 -0
- package/dist/lib/templates/guards/permission.guard.eta +168 -0
- package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
- package/dist/lib/templates/guards/scope.guard.eta +189 -41
- package/dist/lib/templates/python/auth.eta +354 -95
- package/dist/lib/templates/python/index-module.eta +7 -7
- package/dist/lib/templates/python/mcp.eta +284 -0
- package/dist/lib/templates/python/models/init.eta +24 -0
- package/dist/lib/templates/python/models/model.eta +30 -61
- package/dist/lib/templates/python/permissions.eta +121 -0
- package/dist/lib/templates/python/routers/router.eta +39 -1
- package/dist/lib/templates/python/schemas/schema-col-array.eta +1 -1
- package/dist/lib/templates/python/schemas/schema.eta +27 -14
- package/dist/lib/templates/python/services/service.eta +38 -15
- package/dist/lib/templates/python/utils/query.eta +52 -25
- package/dist/lib/templates/rest/controller-rest.eta +43 -23
- package/dist/lib/templates/rest/index-module-rest.eta +0 -4
- package/dist/lib/templates/rest/service-rest.eta +3 -44
- package/dist/lib/types/auth.d.ts +84 -80
- package/dist/lib/types/auth.js +77 -60
- package/dist/lib/types/entity.d.ts +17 -9
- package/dist/lib/types/entity.js +3 -0
- package/dist/lib/types/index.d.ts +2 -2
- package/dist/lib/types/index.js +6 -5
- package/dist/lib/utils/crud-deps.d.ts +77 -6
- package/dist/lib/utils/crud-deps.js +197 -14
- package/dist/lib/utils/field.d.ts +12 -0
- package/dist/lib/utils/field.js +18 -2
- package/dist/lib/utils/schema-convert.d.ts +20 -43
- package/dist/lib/utils/schema-convert.js +28 -78
- package/dist/lib/utils/template.d.ts +11 -0
- package/dist/lib/utils/template.js +36 -1
- package/dist/lib/verify/index.d.ts +6 -1
- package/dist/lib/verify/index.js +30 -13
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +36 -1
- package/package.json +1 -1
- package/dist/lib/templates/go/models/model-col-array.eta +0 -1
- package/dist/lib/templates/go/models/model-col-boolean.eta +0 -1
- package/dist/lib/templates/go/models/model-col-date.eta +0 -1
- package/dist/lib/templates/go/models/model-col-decimal.eta +0 -1
- package/dist/lib/templates/go/models/model-col-enum.eta +0 -2
- package/dist/lib/templates/go/models/model-col-float.eta +0 -1
- package/dist/lib/templates/go/models/model-col-integer.eta +0 -1
- package/dist/lib/templates/go/models/model-col-json.eta +0 -1
- package/dist/lib/templates/go/models/model-col-jsonb.eta +0 -1
- package/dist/lib/templates/go/models/model-col-numeric.eta +0 -1
- package/dist/lib/templates/go/models/model-col-string.eta +0 -1
- package/dist/lib/templates/go/models/model-col-text.eta +0 -1
- package/dist/lib/templates/go/models/model-col-timestamp.eta +0 -1
- package/dist/lib/templates/go/models/model-col-timestamptz.eta +0 -1
- package/dist/lib/templates/go/models/model-col-uuid.eta +0 -1
- package/dist/lib/templates/go/models/model-col-varchar.eta +0 -1
- package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
- package/dist/lib/templates/guards/auth.guard.eta +0 -233
- package/dist/lib/templates/python/models/model-col-array.eta +0 -4
- package/dist/lib/templates/python/models/model-col-boolean.eta +0 -6
- package/dist/lib/templates/python/models/model-col-date.eta +0 -4
- package/dist/lib/templates/python/models/model-col-datetime.eta +0 -5
- package/dist/lib/templates/python/models/model-col-decimal.eta +0 -4
- package/dist/lib/templates/python/models/model-col-enum.eta +0 -16
- package/dist/lib/templates/python/models/model-col-float.eta +0 -6
- package/dist/lib/templates/python/models/model-col-integer.eta +0 -6
- package/dist/lib/templates/python/models/model-col-json.eta +0 -4
- package/dist/lib/templates/python/models/model-col-jsonb.eta +0 -4
- package/dist/lib/templates/python/models/model-col-numeric.eta +0 -4
- package/dist/lib/templates/python/models/model-col-string.eta +0 -6
- package/dist/lib/templates/python/models/model-col-text.eta +0 -6
- package/dist/lib/templates/python/models/model-col-timestamp.eta +0 -11
- package/dist/lib/templates/python/models/model-col-timestamptz.eta +0 -11
- package/dist/lib/templates/python/models/model-col-uuid.eta +0 -5
- package/dist/lib/templates/python/models/model-col-varchar.eta +0 -6
|
@@ -7,10 +7,12 @@ import (
|
|
|
7
7
|
"fmt"
|
|
8
8
|
"math"
|
|
9
9
|
"net/url"
|
|
10
|
+
"reflect"
|
|
10
11
|
"regexp"
|
|
11
12
|
"strconv"
|
|
12
13
|
"strings"
|
|
13
14
|
|
|
15
|
+
"app/autogen/middleware"
|
|
14
16
|
"gorm.io/gorm"
|
|
15
17
|
)
|
|
16
18
|
|
|
@@ -23,10 +25,23 @@ const (
|
|
|
23
25
|
// ErrQuery is a client-facing (HTTP 400) query error. The generated handler
|
|
24
26
|
// maps any *QueryError to a 400 response so a malformed dialect request never
|
|
25
27
|
// surfaces as a 500 (apso #60).
|
|
26
|
-
type QueryError struct{
|
|
28
|
+
type QueryError struct {
|
|
29
|
+
Msg string
|
|
30
|
+
// Forbidden makes the handler answer 403: the query is well formed, and
|
|
31
|
+
// the caller may not run it.
|
|
32
|
+
Forbidden bool
|
|
33
|
+
}
|
|
27
34
|
|
|
28
35
|
func (e *QueryError) Error() string { return e.Msg }
|
|
29
36
|
|
|
37
|
+
// Status is the HTTP status the handler answers with.
|
|
38
|
+
func (e *QueryError) Status() int {
|
|
39
|
+
if e.Forbidden {
|
|
40
|
+
return 403
|
|
41
|
+
}
|
|
42
|
+
return 400
|
|
43
|
+
}
|
|
44
|
+
|
|
30
45
|
func queryErr(format string, a ...interface{}) *QueryError {
|
|
31
46
|
return &QueryError{Msg: fmt.Sprintf(format, a...)}
|
|
32
47
|
}
|
|
@@ -710,7 +725,7 @@ func ApplyQueryE(db *gorm.DB, opts QueryOptions, allowedFields map[string]bool)
|
|
|
710
725
|
if strings.EqualFold(s.Direction, "DESC") {
|
|
711
726
|
dir = "DESC"
|
|
712
727
|
}
|
|
713
|
-
clause := fmt.Sprintf("%s %s", s.Field, dir)
|
|
728
|
+
clause := fmt.Sprintf("%s %s", quoteColumn(s.Field), dir)
|
|
714
729
|
if s.Nulls != "" {
|
|
715
730
|
clause = fmt.Sprintf("%s %s", clause, s.Nulls)
|
|
716
731
|
}
|
|
@@ -723,11 +738,16 @@ func ApplyQueryE(db *gorm.DB, opts QueryOptions, allowedFields map[string]bool)
|
|
|
723
738
|
var safe []string
|
|
724
739
|
for _, f := range opts.Fields {
|
|
725
740
|
col := f
|
|
741
|
+
alias := ""
|
|
726
742
|
if i := strings.Index(strings.ToUpper(f), " AS "); i != -1 {
|
|
727
743
|
col = strings.TrimSpace(f[:i])
|
|
744
|
+
alias = strings.TrimSpace(f[i+4:])
|
|
728
745
|
}
|
|
729
|
-
if allowedFields[col] {
|
|
730
|
-
safe = append(safe,
|
|
746
|
+
if allowedFields[col] && alias != "" {
|
|
747
|
+
safe = append(safe, quoteColumn(col)+" AS "+quoteColumn(alias))
|
|
748
|
+
} else if allowedFields[col] {
|
|
749
|
+
// gorm quotes a bare column name itself.
|
|
750
|
+
safe = append(safe, col)
|
|
731
751
|
} else if postgrest {
|
|
732
752
|
return query, 0, 1, queryErr("Unknown column '%s' in select", col)
|
|
733
753
|
}
|
|
@@ -739,7 +759,15 @@ func ApplyQueryE(db *gorm.DB, opts QueryOptions, allowedFields map[string]bool)
|
|
|
739
759
|
|
|
740
760
|
// Joins (Preloads)
|
|
741
761
|
for _, j := range opts.Joins {
|
|
742
|
-
|
|
762
|
+
// Every relation a request loads (join or select embed) is checked for the caller.
|
|
763
|
+
loads, refused := middleware.RelationLoads(query.Statement.Context, modelName(query), j.Relation)
|
|
764
|
+
if refused != "" {
|
|
765
|
+
return query, 0, 1, &QueryError{Forbidden: true, Msg: fmt.Sprintf("The relation %q cannot be loaded from %s: its rows are tenant-scoped", refused, modelName(query))}
|
|
766
|
+
}
|
|
767
|
+
// Each step of the path, so a tenant-scoped step loads the caller's rows only.
|
|
768
|
+
for _, load := range loads {
|
|
769
|
+
query = query.Preload(preloadName(load.Path), load.Conds...)
|
|
770
|
+
}
|
|
743
771
|
}
|
|
744
772
|
|
|
745
773
|
// Pagination
|
|
@@ -763,6 +791,37 @@ func ApplyQueryE(db *gorm.DB, opts QueryOptions, allowedFields map[string]bool)
|
|
|
763
791
|
return query, total, pageCount, nil
|
|
764
792
|
}
|
|
765
793
|
|
|
794
|
+
// modelName is the entity a query starts from (the struct passed to Model).
|
|
795
|
+
func modelName(query *gorm.DB) string {
|
|
796
|
+
t := reflect.TypeOf(query.Statement.Model)
|
|
797
|
+
for t != nil && (t.Kind() == reflect.Ptr || t.Kind() == reflect.Slice) {
|
|
798
|
+
t = t.Elem()
|
|
799
|
+
}
|
|
800
|
+
if t == nil {
|
|
801
|
+
return ""
|
|
802
|
+
}
|
|
803
|
+
return t.Name()
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// quoteColumn quotes an allowlisted column name: the columns keep their
|
|
807
|
+
// .apsorc names, so seenAt must not fold to seenat.
|
|
808
|
+
func quoteColumn(c string) string {
|
|
809
|
+
return `"` + strings.ReplaceAll(c, `"`, `""`) + `"`
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// preloadName turns a relation as the .apsorc names it (author, posts,
|
|
813
|
+
// author.profile) into the Go field path gorm preloads (Author, Posts,
|
|
814
|
+
// Author.Profile), so ?join= takes the same names as TypeScript and Python.
|
|
815
|
+
func preloadName(relation string) string {
|
|
816
|
+
parts := strings.Split(relation, ".")
|
|
817
|
+
for i, p := range parts {
|
|
818
|
+
if p != "" {
|
|
819
|
+
parts[i] = strings.ToUpper(p[:1]) + p[1:]
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
return strings.Join(parts, ".")
|
|
823
|
+
}
|
|
824
|
+
|
|
766
825
|
// buildGroupExpr turns a PostgREST FilterGroup into a nested GORM expression
|
|
767
826
|
// (a *gorm.DB usable as a Where argument). Unknown columns are a client error
|
|
768
827
|
// (400). Returns nil when the group produced no applicable condition.
|
|
@@ -861,6 +920,7 @@ func parseJoinParam(raw string) ParsedJoin {
|
|
|
861
920
|
// ---------------------------------------------------------------------------
|
|
862
921
|
|
|
863
922
|
func applyOperator(query *gorm.DB, field, op, value string, useOr bool) *gorm.DB {
|
|
923
|
+
field = quoteColumn(field)
|
|
864
924
|
where := query.Where
|
|
865
925
|
if useOr {
|
|
866
926
|
where = query.Or
|
|
@@ -960,9 +1020,10 @@ func splitValue(value string) []string {
|
|
|
960
1020
|
// Booleans and numbers are converted so the database driver sends the
|
|
961
1021
|
// correct wire type instead of a raw string.
|
|
962
1022
|
func coerceValue(value string) interface{} {
|
|
1023
|
+
// "1" and "0" stay numbers: an id or count filter of 1 is not a boolean.
|
|
963
1024
|
low := strings.ToLower(value)
|
|
964
|
-
if low == "true" || low == "false" || low == "yes" || low == "no"
|
|
965
|
-
return low == "true" || low == "yes"
|
|
1025
|
+
if low == "true" || low == "false" || low == "yes" || low == "no" {
|
|
1026
|
+
return low == "true" || low == "yes"
|
|
966
1027
|
}
|
|
967
1028
|
if v, err := strconv.ParseInt(value, 10, 64); err == nil {
|
|
968
1029
|
return v
|
|
@@ -7,9 +7,13 @@ import { APP_GUARD } from '@nestjs/core';
|
|
|
7
7
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
8
8
|
import { ScopeGuard } from './scope.guard';
|
|
9
9
|
<% } %>
|
|
10
|
+
import { ApiKeyGuard<% if (it.mcpAuth) { %>, McpAuthProvider<% } %> } from './key.guard';
|
|
10
11
|
<% if (it.hasAuth) { %>
|
|
11
12
|
import { AuthGuard } from './auth.guard';
|
|
12
13
|
<% } %>
|
|
14
|
+
<% if (it.permissions) { %>
|
|
15
|
+
import { PermissionGuard } from './permission.guard';
|
|
16
|
+
<% } %>
|
|
13
17
|
|
|
14
18
|
<% /* Import all entities for ScopeGuard (from sibling autogen folders) */ %>
|
|
15
19
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
@@ -19,33 +23,24 @@ import { <%= entity.name %> } from '../<%= entity.name %>/<%= entity.name %>.ent
|
|
|
19
23
|
<% }) %>
|
|
20
24
|
<% } %>
|
|
21
25
|
|
|
22
|
-
<% /* Import entities for AuthGuard (from sibling autogen folders) */ %>
|
|
23
|
-
<% if (it.authEntities.length > 0) { %>
|
|
24
|
-
// Entities for AuthGuard
|
|
25
|
-
<% it.authEntities.forEach((entity) => { %>
|
|
26
|
-
import { <%= entity %> } from '../<%= entity %>/<%= entity %>.entity';
|
|
27
|
-
<% }) %>
|
|
28
|
-
<% } %>
|
|
29
|
-
|
|
30
26
|
/**
|
|
31
|
-
* GuardsModule
|
|
27
|
+
* GuardsModule turns on the service's global guards. Every request is refused
|
|
28
|
+
* unless a guard lets it through; a route opts out with @Public().
|
|
32
29
|
*
|
|
33
30
|
* Auto-generated from .apsorc configuration.
|
|
34
31
|
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* and tenant-scoped unless a route opts out with @Public().
|
|
40
|
-
* 3. Services with no auth model generate no guards and rely on the API Gateway
|
|
41
|
-
* API key at the edge.
|
|
42
|
-
*
|
|
32
|
+
* ApiKeyGuard (in every service):
|
|
33
|
+
* - Checks the x-api-key header against the key source chosen at start-up
|
|
34
|
+
* (APSO_API_KEY, else the platform gateway's service token, else off)
|
|
35
|
+
* - A caller with a valid key is a service caller: any route, no tenant scope
|
|
43
36
|
<% if (it.hasAuth) { %>
|
|
44
|
-
* AuthGuard
|
|
45
|
-
* -
|
|
46
|
-
|
|
47
|
-
*
|
|
37
|
+
* - A request with no key goes to AuthGuard (<%= it.authProvider %>), which
|
|
38
|
+
* attaches the signed-in user's AuthContext to request.auth
|
|
39
|
+
<% } else { %>
|
|
40
|
+
* - No sign-in is configured (.apsorc has no auth block), so a request with no
|
|
41
|
+
* valid key is refused
|
|
48
42
|
<% } %>
|
|
43
|
+
*
|
|
49
44
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
50
45
|
* ScopeGuard:
|
|
51
46
|
* - Enforces data isolation based on scopeBy config
|
|
@@ -67,7 +62,6 @@ import { <%= entity %> } from '../<%= entity %>/<%= entity %>.entity';
|
|
|
67
62
|
<% /* Collect all unique entities */ %>
|
|
68
63
|
<% const allEntities = new Set(); %>
|
|
69
64
|
<% if (it.scopedEntities) { it.scopedEntities.forEach(e => allEntities.add(e.name)); } %>
|
|
70
|
-
<% it.authEntities.forEach(e => allEntities.add(e)); %>
|
|
71
65
|
<% const entityArray = Array.from(allEntities); %>
|
|
72
66
|
<% entityArray.forEach((entity, index) => { %>
|
|
73
67
|
<%= entity %><%= index < entityArray.length - 1 ? ',' : '' %>
|
|
@@ -75,21 +69,31 @@ import { <%= entity %> } from '../<%= entity %>/<%= entity %>.entity';
|
|
|
75
69
|
]),
|
|
76
70
|
],
|
|
77
71
|
providers: [
|
|
72
|
+
ApiKeyGuard,
|
|
78
73
|
<% if (it.hasAuth) { %>
|
|
79
74
|
AuthGuard,
|
|
80
75
|
<% } %>
|
|
76
|
+
<% if (it.mcpAuth) { %>
|
|
77
|
+
McpAuthProvider,
|
|
78
|
+
<% } %>
|
|
79
|
+
<% if (it.permissions) { %>
|
|
80
|
+
PermissionGuard,
|
|
81
|
+
<% } %>
|
|
81
82
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
82
83
|
ScopeGuard,
|
|
83
84
|
<% } %>
|
|
84
|
-
// Global guards
|
|
85
|
-
//
|
|
86
|
-
// config generate no guards at all and are protected at the edge by the
|
|
87
|
-
// API Gateway API key — so this does not conflict with that setup. Use the
|
|
88
|
-
// @Public() decorator to opt an individual route out of authentication.
|
|
89
|
-
<% if (it.hasAuth) { %>
|
|
85
|
+
// Global guards, in the order they run. ApiKeyGuard checks an API key and
|
|
86
|
+
// hands a request without one to AuthGuard when sign-in is configured.
|
|
90
87
|
{
|
|
91
88
|
provide: APP_GUARD,
|
|
92
|
-
|
|
89
|
+
useExisting: ApiKeyGuard,
|
|
90
|
+
},
|
|
91
|
+
<% if (it.permissions) { %>
|
|
92
|
+
// Global guards run in this order: roles are checked after the caller is
|
|
93
|
+
// known and before the scope guard loads any rows.
|
|
94
|
+
{
|
|
95
|
+
provide: APP_GUARD,
|
|
96
|
+
useClass: PermissionGuard,
|
|
93
97
|
},
|
|
94
98
|
<% } %>
|
|
95
99
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
@@ -100,9 +104,13 @@ import { <%= entity %> } from '../<%= entity %>/<%= entity %>.entity';
|
|
|
100
104
|
<% } %>
|
|
101
105
|
],
|
|
102
106
|
exports: [
|
|
107
|
+
ApiKeyGuard,
|
|
103
108
|
<% if (it.hasAuth) { %>
|
|
104
109
|
AuthGuard,
|
|
105
110
|
<% } %>
|
|
111
|
+
<% if (it.permissions) { %>
|
|
112
|
+
PermissionGuard,
|
|
113
|
+
<% } %>
|
|
106
114
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
107
115
|
ScopeGuard,
|
|
108
116
|
<% } %>
|
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
<%~ includeFile('../header.eta') %>
|
|
2
2
|
|
|
3
|
+
export * from './key.guard';
|
|
3
4
|
<% if (it.hasAuth) { %>
|
|
4
5
|
export * from './auth.guard';
|
|
5
6
|
<% } %>
|
|
7
|
+
<% if (it.permissions) { %>
|
|
8
|
+
export { PermissionGuard, ENTITY_PERMISSIONS, Permission } from './permission.guard';
|
|
9
|
+
<% } %>
|
|
6
10
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
7
11
|
<% if (it.hasAuth) { %>
|
|
8
12
|
// When auth is configured, only export scope-specific items from scope.guard
|
|
@@ -1,16 +1,34 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* AuthGuard - verifies <%= it.jwt.provider %> JWTs against the issuer's JWKS
|
|
2
|
+
* AuthGuard - verifies <%= it.jwt.map((p) => p.provider).join(', ') %> JWTs against the issuer's JWKS
|
|
3
3
|
*
|
|
4
4
|
* Auto-generated by Apso CLI from .apsorc auth configuration
|
|
5
5
|
*
|
|
6
6
|
* This guard:
|
|
7
7
|
* - Reads the token from the Authorization: Bearer header
|
|
8
|
-
* -
|
|
9
|
-
*
|
|
10
|
-
* -
|
|
8
|
+
* - Picks the provider whose issuer is the token's iss claim. A token from an
|
|
9
|
+
* issuer that is not configured is refused, and no other provider is tried
|
|
10
|
+
* - Verifies its signature with that issuer's published keys, plus issuer,
|
|
11
|
+
* expiry, audience (when one is configured) and algorithm
|
|
12
|
+
* - Maps the token's claims, by that provider's claim names, into a
|
|
13
|
+
* normalized AuthContext on request.auth
|
|
14
|
+
<% if (it.jwt.some((p) => p.provider === 'better-auth')) { %>
|
|
11
15
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
16
|
+
* Better Auth issues two kinds of token, signed with the same keys:
|
|
17
|
+
* - The JWT plugin's token, which the app's own front end sends. Its iss and
|
|
18
|
+
* aud are Better Auth's baseURL option, normally the origin of the URL in
|
|
19
|
+
* .apsorc, so that origin is accepted as an issuer and is the default
|
|
20
|
+
* audience (AUTH_JWT_AUDIENCE or auth.jwt.audience changes it).
|
|
21
|
+
* - An OAuth access token (header type at+jwt) issued to an MCP client. Its
|
|
22
|
+
* iss is the URL in .apsorc and its aud is the resource it was issued for:
|
|
23
|
+
* MCP_RESOURCE_URL, or the audience above. It must name its client in azp.
|
|
24
|
+
* A session cookie or session token is not a JWT and is refused.
|
|
25
|
+
<% } %>
|
|
26
|
+
*
|
|
27
|
+
* AUTH_JWT_ISSUER, AUTH_JWT_AUDIENCE, AUTH_JWKS_URI and
|
|
28
|
+
* AUTH_JWT_AUTHORIZED_PARTIES override the .apsorc values at runtime (for
|
|
29
|
+
* example a staging and a production tenant). With several providers they
|
|
30
|
+
* set the first; the second reads the same names ending in _2
|
|
31
|
+
* (AUTH_JWT_ISSUER_2), and so on.
|
|
14
32
|
*
|
|
15
33
|
* DO NOT EDIT - Changes will be overwritten on next scaffold
|
|
16
34
|
*/
|
|
@@ -21,7 +39,7 @@ import {
|
|
|
21
39
|
UnauthorizedException,
|
|
22
40
|
} from '@nestjs/common';
|
|
23
41
|
import { Reflector } from '@nestjs/core';
|
|
24
|
-
import { createRemoteJWKSet, jwtVerify, JWTPayload } from 'jose';
|
|
42
|
+
import { createRemoteJWKSet, decodeJwt,<% if (it.jwt.some((p) => p.provider === 'better-auth')) { %> decodeProtectedHeader,<% } %> jwtVerify, JWTPayload } from 'jose';
|
|
25
43
|
|
|
26
44
|
export const IS_PUBLIC_KEY = 'isPublic';
|
|
27
45
|
|
|
@@ -44,18 +62,51 @@ export interface AuthContext {
|
|
|
44
62
|
workspaceId?: string;
|
|
45
63
|
organizationId?: string;
|
|
46
64
|
roles: string[];
|
|
65
|
+
/** Permission strings from the token ("invoice:delete"), read by PermissionGuard. */
|
|
66
|
+
permissions: string[];
|
|
67
|
+
/** The issuer that signed the caller in, and its provider type in .apsorc. */
|
|
68
|
+
issuer: string;
|
|
69
|
+
provider: string;
|
|
47
70
|
claims: JWTPayload;
|
|
48
71
|
}
|
|
49
72
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
73
|
+
<% if (it.mcpAuth) { %>
|
|
74
|
+
// Public URL of the MCP endpoint (https://api.example.com/mcp). MCP clients ask
|
|
75
|
+
// the identity provider for a token for this URL, so it is an accepted audience.
|
|
76
|
+
const MCP_RESOURCE = process.env.MCP_RESOURCE_URL || '';
|
|
77
|
+
<% } else { %>
|
|
78
|
+
const MCP_RESOURCE = '';
|
|
79
|
+
<% } %>
|
|
80
|
+
|
|
81
|
+
/** One trusted issuer: its own keys, audience and claim names. */
|
|
82
|
+
const PROVIDERS = (<%~ JSON.stringify(it.jwt) %> as any[]).map((p, i) => {
|
|
83
|
+
// The first provider reads AUTH_JWT_ISSUER, the second AUTH_JWT_ISSUER_2, and so on.
|
|
84
|
+
const env = (name: string) => process.env[i === 0 ? name : `${name}_${i + 1}`];
|
|
85
|
+
const issuer = env('AUTH_JWT_ISSUER') || (p.issuer as string);
|
|
86
|
+
// Better Auth's JWT plugin signs with the origin of its URL as iss and aud.
|
|
87
|
+
const origin = p.provider === 'better-auth' ? new URL(issuer).origin : '';
|
|
88
|
+
const audience = env('AUTH_JWT_AUDIENCE') || p.audience || origin;
|
|
89
|
+
return {
|
|
90
|
+
provider: p.provider as string,
|
|
91
|
+
issuer,
|
|
92
|
+
issuers: origin ? [...new Set([issuer, origin])] : [issuer],
|
|
93
|
+
audience,
|
|
94
|
+
// No configured audience means none is checked (Clerk and Cognito tokens carry no aud).
|
|
95
|
+
audiences: audience ? [audience, MCP_RESOURCE].filter(Boolean) : [],
|
|
96
|
+
jwks: createRemoteJWKSet(new URL(env('AUTH_JWKS_URI') || p.jwksUri)),
|
|
97
|
+
algorithms: p.algorithms as string[],
|
|
98
|
+
authorizedParties: (env('AUTH_JWT_AUTHORIZED_PARTIES') || p.authorizedParties.join(','))
|
|
99
|
+
.split(',')
|
|
100
|
+
.map((s: string) => s.trim())
|
|
101
|
+
.filter(Boolean) as string[],
|
|
102
|
+
claims: p.claims as Record<string, string | undefined>,
|
|
103
|
+
};
|
|
104
|
+
});
|
|
105
|
+
const BY_ISSUER = new Map(PROVIDERS.flatMap((p) => p.issuers.map((issuer) => [issuer, p] as const)));
|
|
106
|
+
if (BY_ISSUER.size !== PROVIDERS.reduce((n, p) => n + p.issuers.length, 0)) {
|
|
107
|
+
// The token's iss picks the provider, so two providers cannot share one.
|
|
108
|
+
throw new Error('[apso] Two auth providers have the same issuer. Check AUTH_JWT_ISSUER and its numbered variants.');
|
|
109
|
+
}
|
|
59
110
|
|
|
60
111
|
/** A claim by exact name (Auth0 namespaced URLs contain dots), else by dotted path. */
|
|
61
112
|
function claim(payload: JWTPayload, path?: string): unknown {
|
|
@@ -74,8 +125,6 @@ function roles(v: unknown): string[] {
|
|
|
74
125
|
|
|
75
126
|
@Injectable()
|
|
76
127
|
export class AuthGuard implements CanActivate {
|
|
77
|
-
private readonly jwks = createRemoteJWKSet(new URL(JWKS_URI));
|
|
78
|
-
|
|
79
128
|
constructor(private reflector: Reflector) {}
|
|
80
129
|
|
|
81
130
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
@@ -93,36 +142,61 @@ export class AuthGuard implements CanActivate {
|
|
|
93
142
|
return true;
|
|
94
143
|
}
|
|
95
144
|
|
|
96
|
-
|
|
145
|
+
await this.authenticate(context.switchToHttp().getRequest());
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Verify the request's bearer token and attach the caller to the request.
|
|
151
|
+
* Throws UnauthorizedException when the token is missing or not accepted.
|
|
152
|
+
*/
|
|
153
|
+
async authenticate(request: any): Promise<AuthContext> {
|
|
97
154
|
const header: string | undefined = request.headers.authorization;
|
|
98
155
|
if (!header || !header.startsWith('Bearer ')) {
|
|
99
156
|
throw new UnauthorizedException('No bearer token provided');
|
|
100
157
|
}
|
|
101
158
|
|
|
159
|
+
const token = header.substring(7);
|
|
102
160
|
let payload: JWTPayload;
|
|
161
|
+
let provider: (typeof PROVIDERS)[number] | undefined;
|
|
103
162
|
try {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
163
|
+
// The token's own issuer picks the provider, before anything is
|
|
164
|
+
// verified; then only that provider's keys and settings are used.
|
|
165
|
+
const iss = decodeJwt(token).iss as string;
|
|
166
|
+
provider = BY_ISSUER.get(iss);
|
|
167
|
+
if (!provider) throw new Error('issuer not configured');
|
|
168
|
+
let audiences = provider.audiences;
|
|
169
|
+
<% if (it.jwt.some((p) => p.provider === 'better-auth')) { %>
|
|
170
|
+
// Better Auth: only an OAuth access token may be one issued for the MCP URL.
|
|
171
|
+
const accessToken = provider.provider === 'better-auth' && decodeProtectedHeader(token).typ === 'at+jwt';
|
|
172
|
+
if (provider.provider === 'better-auth' && !accessToken) audiences = [provider.audience];
|
|
109
173
|
<% } %>
|
|
174
|
+
({ payload } = await jwtVerify(token, provider.jwks, {
|
|
175
|
+
issuer: iss,
|
|
176
|
+
algorithms: provider.algorithms,
|
|
177
|
+
// Cognito's audience is checked below.
|
|
178
|
+
audience: provider.provider !== 'cognito' && audiences.length > 0 ? audiences : undefined,
|
|
110
179
|
}));
|
|
180
|
+
<% if (it.jwt.some((p) => p.provider === 'better-auth')) { %>
|
|
181
|
+
if (accessToken && typeof (payload as any).azp !== 'string') throw new Error('access token without azp');
|
|
182
|
+
<% } %>
|
|
111
183
|
} catch {
|
|
112
184
|
throw new UnauthorizedException('Invalid token');
|
|
113
185
|
}
|
|
114
|
-
|
|
186
|
+
const { authorizedParties, claims: CLAIMS } = provider;
|
|
187
|
+
<% if (it.jwt.some((p) => p.provider === 'cognito')) { %>
|
|
115
188
|
// Cognito ID tokens carry aud; access tokens carry client_id instead.
|
|
116
|
-
if (
|
|
189
|
+
if (provider.provider === 'cognito' && provider.audiences.length > 0) {
|
|
117
190
|
const aud = payload.aud ?? (payload as any).client_id;
|
|
118
|
-
|
|
191
|
+
const given: unknown[] = Array.isArray(aud) ? aud : [aud];
|
|
192
|
+
if (!given.some((value) => provider.audiences.includes(value as string))) {
|
|
119
193
|
throw new UnauthorizedException('Invalid token');
|
|
120
194
|
}
|
|
121
195
|
}
|
|
122
196
|
<% } %>
|
|
123
197
|
|
|
124
198
|
const azp = (payload as any).azp;
|
|
125
|
-
if (
|
|
199
|
+
if (authorizedParties.length > 0 && azp !== undefined && !authorizedParties.includes(azp)) {
|
|
126
200
|
throw new UnauthorizedException('Invalid token');
|
|
127
201
|
}
|
|
128
202
|
|
|
@@ -139,6 +213,9 @@ export class AuthGuard implements CanActivate {
|
|
|
139
213
|
workspaceId: tenant,
|
|
140
214
|
organizationId: tenant,
|
|
141
215
|
roles: roles(claim(payload, CLAIMS.roles)),
|
|
216
|
+
permissions: roles(claim(payload, CLAIMS.permissions)),
|
|
217
|
+
issuer: payload.iss as string,
|
|
218
|
+
provider: provider.provider,
|
|
142
219
|
claims: payload,
|
|
143
220
|
};
|
|
144
221
|
|
|
@@ -147,9 +224,17 @@ export class AuthGuard implements CanActivate {
|
|
|
147
224
|
// Read by ScopeGuard's scope lookup.
|
|
148
225
|
request.workspaceId = tenant;
|
|
149
226
|
request.organizationId = tenant;
|
|
150
|
-
return
|
|
227
|
+
return auth;
|
|
151
228
|
}
|
|
152
229
|
}
|
|
230
|
+
<% if (it.mcpAuth) { %>
|
|
231
|
+
|
|
232
|
+
/** Where MCP clients sign in. ApiKeyGuard adds the credential check for @apso/mcp. */
|
|
233
|
+
export const MCP_SIGN_IN = {
|
|
234
|
+
authorizationServers: PROVIDERS.map((p) => p.issuer),
|
|
235
|
+
resource: MCP_RESOURCE || undefined,
|
|
236
|
+
};
|
|
237
|
+
<% } %>
|
|
153
238
|
|
|
154
239
|
/**
|
|
155
240
|
* Helper function to get AuthContext from request
|