From 1ae134d609d6e83ba5e10710e3b20dc4e5da162d Mon Sep 17 00:00:00 2001 From: Gabriel Nordeborn Date: Sat, 1 Aug 2026 23:05:09 +0200 Subject: [PATCH 1/6] Add selection-wide authorization coverage --- CHANGELOG.md | 4 + docs/docs/authorization.md | 41 ++- src/ml/GenerateSchemaAuthorization.ml | 242 ++++++++++++++++-- src/ml/GenerateSchemaDirect.ml | 3 +- src/ml/GenerateSchemaTypePrinters.ml | 1 + src/ml/GenerateSchemaTypes.ml | 9 + src/ml/GenerateSchemaUtils.ml | 84 +++++- src/res/ResGraph.res | 3 + tests/authorization/baseline/src/ResGraph.res | 3 + tests/authorization/invalid/src/Query.res | 19 +- tests/authorization/invalid/src/ResGraph.res | 3 + tests/authorization/invalid/src/Security.res | 2 + tests/authorization/run-tests.sh | 21 ++ .../expected-authorization-manifest.json | 7 +- tests/authorization/valid/src/Query.res | 8 + tests/authorization/valid/src/ResGraph.res | 3 + tests/authorization/valid/src/Security.res | 5 + .../valid/src/SelectionCoverage.res | 20 ++ 18 files changed, 442 insertions(+), 36 deletions(-) create mode 100644 tests/authorization/valid/src/SelectionCoverage.res diff --git a/CHANGELOG.md b/CHANGELOG.md index 005273a2..a4d1e8ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- Allow field authorization policies to cover their returned selection with + `{covers: Selection}`, including statically validated path coverage and + authorization-manifest provenance without repeated policy evaluation. + ## 1.3.0 - Add opt-in required authorization coverage with typed `.authorize` policies, explicit `.public` dispositions, resolver outcomes, mutation prechecks, interface policy inheritance, custom forbidden handlers, and deterministic audit manifests. diff --git a/docs/docs/authorization.md b/docs/docs/authorization.md index 9d105c10..7307dd8d 100644 --- a/docs/docs/authorization.md +++ b/docs/docs/authorization.md @@ -85,7 +85,44 @@ A policy must have: Type, interface, field, and resolver policies compose additively. Interface field public dispositions and interface resolver outcomes also propagate to concrete implementations. Policies execute in declaration order with AND semantics and stop at the first `Forbidden`. Converted field arguments are constructed once and shared by every policy and the resolver. Async code is generated only when a policy or outcome is promise-backed. -A policy on a field returning an object does not authorize that object's child fields. Each output field needs its own disposition. +By default, a policy on a field returning an object does not authorize that +object's child fields. Each output field needs its own disposition. + +### Covering a returned selection + +A field policy can explicitly cover the selection returned beneath that field. +This is useful for connection wrappers, mutation payloads, and calculated result +objects that have no authorization identity independent of the field producing +them: + +```rescript +@gql.authorize( + (CampaignSecurity.canList, {ResGraph.Authorization.covers: Selection}) +) +@gql.field +let campaigns = async ( + _: query, + ~organizationId: string, + ~ctx: ResGraphContext.context, +): campaignConnection => { + await ctx.dataLoaders.campaigns.load(~organizationId) +} +``` + +The inner parentheses form the ReScript tuple consumed by `@gql.authorize`. +The qualified record label gives ReScript the configuration type, from which it +infers and checks the `Selection` constructor. + +The policy runs once on `Query.campaigns`. Required authorization treats fields +reachable exclusively beneath that result as selection-covered, without +generating additional policy calls for them. Local type and field policies +still run and compose additively when present. + +Selection coverage is path-sensitive. If the same result type is also reachable +through a path without a selection-covering policy, its otherwise-uncovered +fields fail required authorization. Public fields and resolver outcomes do not +establish selection coverage. `covers: Selection` is supported only on output +fields and resolver functions, not on type policies. ## Resolver outcomes @@ -137,7 +174,7 @@ let onForbidden = ( ## Audit manifest and boundaries -`manifestPath` emits stable, sorted JSON with every concrete field, its disposition, policy order and provenance, public reason, source locations, resolver-outcome metadata, and mutation status. Commit it when authorization posture should be reviewed through diffs. +`manifestPath` emits stable, sorted JSON with every concrete field, its disposition, policy order and provenance, inherited selection boundaries, public reason, source locations, resolver-outcome metadata, and mutation status. For a field reachable through multiple covered paths, `selectionCoverage` lists the possible boundary sources; only the boundary on the selected runtime path executes. Commit the manifest when authorization posture should be reviewed through diffs. Fields on inferred union payload objects use the `synthetic` disposition. They have no annotation surface and are reachable only after their parent resolver diff --git a/src/ml/GenerateSchemaAuthorization.ml b/src/ml/GenerateSchemaAuthorization.ml index 696de9a1..c154f32f 100644 --- a/src/ml/GenerateSchemaAuthorization.ml +++ b/src/ml/GenerateSchemaAuthorization.ml @@ -394,7 +394,7 @@ let loadBaseline path = BaselineEntries.empty let gapForField ~(typ : gqlObjectType) ~(field : gqlField) ~synthetic ~public - ~references ~resolverOutcome = + ~references ~inheritedSelectionPolicies ~resolverOutcome = let coordinate = GenerateSchemaUtils.authorizationCoordinate ~parentTypeName:typ.displayName ~fieldName:field.name @@ -402,7 +402,9 @@ let gapForField ~(typ : gqlObjectType) ~(field : gqlField) ~synthetic ~public if typ.id = "subscription" then Some (coordinate, UnsupportedSubscription) else if synthetic then None else if - Option.is_none public && references = [] && Option.is_none resolverOutcome + Option.is_none public && references = [] + && inheritedSelectionPolicies = [] + && Option.is_none resolverOutcome then Some (coordinate, UncoveredField) else if typ.id = "mutation" && Option.is_none public && references = [] then Some (coordinate, MutationPreResolverPolicy) @@ -434,8 +436,7 @@ let addGapDiagnostic schemaState ~(field : gqlField) (coordinate, kind) = ~diagnostic:{loc = field.loc; fileUri = field.fileUri; message} let buildFieldPlan ~loader ~package ~(schemaState : schemaState) - ~baselineEntries ~skipGapDiagnostics ~(typ : gqlObjectType) - ~(field : gqlField) = + ~(typ : gqlObjectType) ~(field : gqlField) = let coordinate = GenerateSchemaUtils.authorizationCoordinate ~parentTypeName:typ.displayName ~fieldName:field.name @@ -494,8 +495,181 @@ let buildFieldPlan ~loader ~package ~(schemaState : schemaState) coordinate; } | _ -> ()); + Hashtbl.replace schemaState.authorizationPlans coordinate + { + functions; + inheritedSelectionPolicies = []; + public; + resolverOutcome; + synthetic; + baselineGap = None; + } + +module InheritedSelectionPolicy = struct + type t = inheritedSelectionPolicy + + let compare = Stdlib.compare +end + +module InheritedSelectionPolicies = Set.Make (InheritedSelectionPolicy) + +type selectionReachability = { + hasUnprotectedPath: bool; + policies: InheritedSelectionPolicies.t; +} + +let rec outputTypeIds ~processedSchema = function + | List inner | Nullable inner | RescriptNullable inner -> + outputTypeIds ~processedSchema inner + | GraphQLObjectType {id} -> [id] + | GraphQLUnion _ -> [] + | GraphQLInterface {id} -> ( + match Hashtbl.find_opt processedSchema.interfaceImplementedBy id with + | None -> [] + | Some implementations -> + implementations + |> List.filter_map (fun (implementation : interfaceImplementedBy) -> + match implementation with + | ObjectType typ -> Some typ.id + | Interface _ -> None)) + | Scalar _ | EmptyPayload | InjectContext | InjectInfo + | InjectInterfaceTypename _ | GraphQLInputObject _ | GraphQLInputUnion _ + | GraphQLEnum _ | GraphQLScalar _ -> + [] + +let unionMemberIds (schemaState : schemaState) = function + | GraphQLUnion {id} -> ( + match Hashtbl.find_opt schemaState.unions id with + | None -> [] + | Some union -> + union.types + |> List.map (fun (member : gqlUnionMember) -> member.objectTypeId)) + | _ -> [] + +let fieldOutputTypeIds ~processedSchema (schemaState : schemaState) + (field : gqlField) = + let rec ids = function + | List inner | Nullable inner | RescriptNullable inner -> ids inner + | GraphQLUnion _ as union -> unionMemberIds schemaState union + | typ -> outputTypeIds ~processedSchema typ + in + ids field.typ |> List.sort_uniq String.compare + +let selectionPolicies coordinate (plan : effectiveAuthorizationPlan) = + plan.functions + |> List.filter_map (fun (fn : authorizationFunction) -> + match fn.reference.covers with + | AuthorizationField -> None + | AuthorizationSelection -> Some {boundaryCoordinate = coordinate; fn}) + |> InheritedSelectionPolicies.of_list + +let updateReachability reachability typeId incoming = + match Hashtbl.find_opt reachability typeId with + | None -> + Hashtbl.add reachability typeId incoming; + true + | Some existing -> + let merged = + { + hasUnprotectedPath = + existing.hasUnprotectedPath || incoming.hasUnprotectedPath; + policies = + InheritedSelectionPolicies.union existing.policies incoming.policies; + } + in + if merged = existing then false + else ( + Hashtbl.replace reachability typeId merged; + true) + +let selectionReachability ~processedSchema (schemaState : schemaState) = + let reachability = Hashtbl.create 50 in + let pending = Queue.create () in + let enqueueRoot = function + | None -> () + | Some (typ : gqlObjectType) -> + if + updateReachability reachability typ.id + { + hasUnprotectedPath = true; + policies = InheritedSelectionPolicies.empty; + } + then Queue.add typ.id pending + in + enqueueRoot schemaState.query; + enqueueRoot schemaState.mutation; + enqueueRoot schemaState.subscription; + while not (Queue.is_empty pending) do + let typeId = Queue.take pending in + match + ( Hashtbl.find_opt schemaState.types typeId, + Hashtbl.find_opt reachability typeId ) + with + | Some typ, Some incoming -> + typ.fields + |> List.iter (fun field -> + let coordinate = + GenerateSchemaUtils.authorizationCoordinate + ~parentTypeName:typ.displayName ~fieldName:field.name + in + let plan = Hashtbl.find schemaState.authorizationPlans coordinate in + let localPolicies = selectionPolicies coordinate plan in + let outgoing = + { + hasUnprotectedPath = + incoming.hasUnprotectedPath + && InheritedSelectionPolicies.is_empty localPolicies; + policies = + InheritedSelectionPolicies.union incoming.policies localPolicies; + } + in + fieldOutputTypeIds ~processedSchema schemaState field + |> List.iter (fun outputTypeId -> + if updateReachability reachability outputTypeId outgoing then + Queue.add outputTypeId pending)) + | _ -> () + done; + reachability + +let applyInheritedSelectionPolicies ~processedSchema (schemaState : schemaState) + = + let reachability = selectionReachability ~processedSchema schemaState in + schemaState.types + |> Hashtbl.iter (fun typeId (typ : gqlObjectType) -> + let inheritedSelectionPolicies = + match Hashtbl.find_opt reachability typeId with + | Some {hasUnprotectedPath = false; policies} + when not (InheritedSelectionPolicies.is_empty policies) -> + InheritedSelectionPolicies.elements policies + | _ -> [] + in + typ.fields + |> List.iter (fun field -> + let coordinate = + GenerateSchemaUtils.authorizationCoordinate + ~parentTypeName:typ.displayName ~fieldName:field.name + in + match Hashtbl.find_opt schemaState.authorizationPlans coordinate with + | None -> () + | Some plan -> + Hashtbl.replace schemaState.authorizationPlans coordinate + {plan with inheritedSelectionPolicies})) + +let finalizeFieldPlan ~(schemaState : schemaState) ~baselineEntries + ~skipGapDiagnostics ~(typ : gqlObjectType) ~(field : gqlField) = + let coordinate = + GenerateSchemaUtils.authorizationCoordinate ~parentTypeName:typ.displayName + ~fieldName:field.name + in + let plan = Hashtbl.find schemaState.authorizationPlans coordinate in + let references = + plan.functions + |> List.map (fun (fn : authorizationFunction) -> fn.reference) + in let gap = - gapForField ~typ ~field ~synthetic ~public ~references ~resolverOutcome + gapForField ~typ ~field ~synthetic:plan.synthetic ~public:plan.public + ~references ~inheritedSelectionPolicies:plan.inheritedSelectionPolicies + ~resolverOutcome:plan.resolverOutcome in let baselineGap = match (schemaState.authorizationConfig.mode, gap, baselineEntries) with @@ -506,7 +680,7 @@ let buildFieldPlan ~loader ~package ~(schemaState : schemaState) | _ -> None in Hashtbl.replace schemaState.authorizationPlans coordinate - {functions; public; resolverOutcome; synthetic; baselineGap}; + {plan with baselineGap}; (match gap with | Some entry -> schemaState.authorizationGaps <- entry :: schemaState.authorizationGaps @@ -537,7 +711,7 @@ let addStaleBaselineDiagnostics schemaState ~path ~baselineEntries = (authorizationGapKindToString kind); }) -let buildPlans ~loader ~package (schemaState : schemaState) = +let buildPlans ~loader ~package ~processedSchema (schemaState : schemaState) = let baselineEntries, baselineLoadFailed = match ( schemaState.authorizationConfig.mode, @@ -558,7 +732,14 @@ let buildPlans ~loader ~package (schemaState : schemaState) = (fun _ (typ : gqlObjectType) -> typ.fields |> List.iter (fun field -> - buildFieldPlan ~loader ~package ~schemaState ~baselineEntries + buildFieldPlan ~loader ~package ~schemaState ~typ ~field)); + applyInheritedSelectionPolicies ~processedSchema schemaState; + schemaState.types + |> GenerateSchemaUtils.iterHashtblAlphabetically + (fun _ (typ : gqlObjectType) -> + typ.fields + |> List.iter (fun field -> + finalizeFieldPlan ~schemaState ~baselineEntries ~skipGapDiagnostics:baselineLoadFailed ~typ ~field)); match (baselineEntries, schemaState.authorizationConfig.baselinePath) with | Some entries, Some path -> @@ -582,13 +763,24 @@ let provenanceToString = function | FieldPolicy coordinate -> "field:" ^ coordinate let manifestPolicy ~package (fn : authorizationFunction) = + let covers = + match fn.reference.covers with + | AuthorizationField -> "" + | AuthorizationSelection -> ",\"covers\":\"selection\"" + in Printf.sprintf - "{\"path\":%s,\"provenance\":%s,\"file\":%s,\"location\":%s,\"async\":%s}" + "{\"path\":%s,\"provenance\":%s,\"file\":%s,\"location\":%s,\"async\":%s%s}" (jsonString (GenerateSchemaUtils.authorizationFunctionName fn.reference)) (jsonString (provenanceToString fn.provenance)) (jsonString (relativeSourcePath ~package fn.reference.fileUri)) (jsonString (Loc.toString fn.reference.loc)) (if fn.isAsync then "true" else "false") + covers + +let manifestInheritedPolicy ~package (policy : inheritedSelectionPolicy) = + Printf.sprintf "{\"boundary\":%s,\"policy\":%s}" + (jsonString policy.boundaryCoordinate) + (manifestPolicy ~package policy.fn) let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = let disposition = @@ -597,14 +789,16 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = plan.synthetic, plan.public, plan.functions, + plan.inheritedSelectionPolicies, plan.resolverOutcome ) with - | Some _, _, _, _, _ -> "baseline" - | None, true, _, _, _ -> "synthetic" - | None, false, Some _, _, _ -> "public" - | None, false, None, _ :: _, _ -> "policies" - | None, false, None, [], Some _ -> "resolverOutcome" - | None, false, None, [], None -> "uncovered" + | Some _, _, _, _, _, _ -> "baseline" + | None, true, _, _, _, _ -> "synthetic" + | None, false, Some _, _, _, _ -> "public" + | None, false, None, _ :: _, _, _ -> "policies" + | None, false, None, [], _, Some _ -> "resolverOutcome" + | None, false, None, [], _ :: _, None -> "selection" + | None, false, None, [], [], None -> "uncovered" in let publicJson = match plan.public with @@ -621,13 +815,22 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = | Some {isAsync} -> Printf.sprintf "{\"async\":%s}" (if isAsync then "true" else "false") in + let inheritedSelectionJson = + match plan.inheritedSelectionPolicies with + | [] -> "" + | policies -> + Printf.sprintf ",\"selectionCoverage\":[%s]" + (policies + |> List.map (manifestInheritedPolicy ~package) + |> String.concat ",") + in Printf.sprintf - "{\"coordinate\":%s,\"disposition\":%s,\"mutation\":%s,\"policies\":[%s],\"public\":%s,\"resolverOutcome\":%s}" + "{\"coordinate\":%s,\"disposition\":%s,\"mutation\":%s,\"policies\":[%s],\"public\":%s,\"resolverOutcome\":%s%s}" (jsonString coordinate) (jsonString disposition) (if String.starts_with coordinate ~prefix:"Mutation." then "true" else "false") (plan.functions |> List.map (manifestPolicy ~package) |> String.concat ",") - publicJson resolverOutcomeJson + publicJson resolverOutcomeJson inheritedSelectionJson let rec ensureDirectory path = if path = "" || path = "." || Sys.file_exists path then () @@ -639,7 +842,7 @@ let generatedManifest ~status ~fields = Printf.sprintf "{\n\ \ \"generatedBy\": \"resgraph\",\n\ - \ \"version\": 1,\n\ + \ \"version\": 2,\n\ \ \"status\": \"%s\",\n\ \ \"fields\": [\n\ \ %s\n\ @@ -655,8 +858,9 @@ let isGeneratedManifest path = | None -> false | Some json -> let status = Option.bind (Json.get "status" json) Json.string in + let version = Option.bind (Json.get "version" json) Json.number in Option.bind (Json.get "generatedBy" json) Json.string = Some "resgraph" - && Option.bind (Json.get "version" json) Json.number = Some 1. + && (version = Some 1. || version = Some 2.) && (status = Some "generationFailed" || status = Some "success") && Option.is_some (Option.bind (Json.get "fields" json) Json.array)) diff --git a/src/ml/GenerateSchemaDirect.ml b/src/ml/GenerateSchemaDirect.ml index 33ab94b8..1821b61a 100644 --- a/src/ml/GenerateSchemaDirect.ml +++ b/src/ml/GenerateSchemaDirect.ml @@ -234,7 +234,8 @@ let generateSchemaDirect ~printToStdOut ~writeStateFile ~sourceFolder ~debug let processedSchema = GenerateSchemaUtils.processSchema schemaState in - GenerateSchemaAuthorization.buildPlans ~loader ~package schemaState; + GenerateSchemaAuthorization.buildPlans ~loader ~package + ~processedSchema schemaState; let markNamedSchemaFile contents = match schemaName with | Some _ -> diff --git a/src/ml/GenerateSchemaTypePrinters.ml b/src/ml/GenerateSchemaTypePrinters.ml index 3c4baeed..62a9ac65 100644 --- a/src/ml/GenerateSchemaTypePrinters.ml +++ b/src/ml/GenerateSchemaTypePrinters.ml @@ -47,6 +47,7 @@ let printResolverForField ~parentTypeName ~(schemaState : schemaState) | None -> { functions = []; + inheritedSelectionPolicies = []; public = None; resolverOutcome = Hashtbl.find_opt schemaState.resolverOutcomes coordinate; diff --git a/src/ml/GenerateSchemaTypes.ml b/src/ml/GenerateSchemaTypes.ml index 4296555a..d4e862ae 100644 --- a/src/ml/GenerateSchemaTypes.ml +++ b/src/ml/GenerateSchemaTypes.ml @@ -39,10 +39,13 @@ type authorizationConfig = { baselinePath: string option; } +type authorizationCoverage = AuthorizationField | AuthorizationSelection + type authorizationFunctionReference = { path: string list; loc: Location.t; fileUri: Uri.t; + covers: authorizationCoverage; } type publicAuthorization = {reason: string; loc: Location.t; fileUri: Uri.t} @@ -76,12 +79,18 @@ type authorizationGapKind = type effectiveAuthorizationPlan = { functions: authorizationFunction list; + inheritedSelectionPolicies: inheritedSelectionPolicy list; public: publicAuthorization option; resolverOutcome: resolverOutcome option; synthetic: bool; baselineGap: authorizationGapKind option; } +and inheritedSelectionPolicy = { + boundaryCoordinate: string; + fn: authorizationFunction; +} + type typeLocationLoc = { fileName: string; fileUri: Uri.t; diff --git a/src/ml/GenerateSchemaUtils.ml b/src/ml/GenerateSchemaUtils.ml index dcdba004..947ecb93 100644 --- a/src/ml/GenerateSchemaUtils.ml +++ b/src/ml/GenerateSchemaUtils.ml @@ -162,8 +162,53 @@ let addAuthorizationDiagnostic ~schemaState ~(env : SharedTypes.QueryEnv.t) ~loc |> addDiagnostic ~diagnostic:{loc; fileUri = env.SharedTypes.QueryEnv.file.uri; message} -let functionReferenceFromPayload ~schemaState ~(env : SharedTypes.QueryEnv.t) - ~attributeLoc (payload : Parsetree.payload) = +let authorizationCoverageFromRecord ~schemaState ~(env : SharedTypes.QueryEnv.t) + ~attributeLoc fields = + let coversFields = + fields + |> List.filter + (fun (field : Parsetree.expression Parsetree.record_element) -> + Longident.last field.lid.txt = "covers") + in + match (fields, coversFields) with + | [_], [field] -> ( + match field.x.pexp_desc with + | Pexp_construct ({txt = constructor}, None) + when Longident.last constructor = "Selection" -> + Some AuthorizationSelection + | _ -> + addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc + "`@gql.authorize` coverage must be the `Selection` constructor, for \ + example `@gql.authorize((Security.canRead, \ + {ResGraph.Authorization.covers: Selection}))`."; + None) + | [], _ | _, [] -> + addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc + "`@gql.authorize` coverage requires `{covers: Selection}` in its tuple \ + payload."; + None + | _ -> + addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc + "`@gql.authorize` coverage accepts only `{covers: Selection}`."; + None + +let functionReferenceFromPayload ~allowSelection ~schemaState + ~(env : SharedTypes.QueryEnv.t) ~attributeLoc (payload : Parsetree.payload) + = + let reference functionPath covers = + let path = Longident.flatten functionPath in + if List.length path < 2 then ( + addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc + "`@gql.authorize` requires a module-qualified function path, for \ + example `Security.canRead`."; + None) + else if covers = AuthorizationSelection && not allowSelection then ( + addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc + "`@gql.authorize((..., {covers: Selection}))` can only be used on \ + output fields or resolver functions, not on a type."; + None) + else Some {path; loc = attributeLoc; fileUri = env.file.uri; covers} + in match payload with | PStr [ @@ -172,13 +217,28 @@ let functionReferenceFromPayload ~schemaState ~(env : SharedTypes.QueryEnv.t) Pstr_eval ({pexp_desc = Pexp_ident {txt = functionPath}}, _); }; ] -> - let path = Longident.flatten functionPath in - if List.length path < 2 then ( - addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.authorize` requires a module-qualified function path, for \ - example `Security.canRead`."; - None) - else Some {path; loc = attributeLoc; fileUri = env.file.uri} + reference functionPath AuthorizationField + | PStr + [ + { + pstr_desc = + Pstr_eval + ( { + pexp_desc = + Pexp_tuple + [ + {pexp_desc = Pexp_ident {txt = functionPath}}; + {pexp_desc = Pexp_record (fields, None)}; + ]; + }, + _ ); + }; + ] -> ( + match + authorizationCoverageFromRecord ~schemaState ~env ~attributeLoc fields + with + | None -> None + | Some covers -> reference functionPath covers) | _ -> addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc "`@gql.authorize` requires a module-qualified function path, for example \ @@ -229,8 +289,8 @@ let extractDeclaredAuthorization ~allowPublic ~schemaState match String.split_on_char '.' name.txt with | ["gql"; "authorize"] -> ( match - functionReferenceFromPayload ~schemaState ~env - ~attributeLoc:name.loc payload + functionReferenceFromPayload ~allowSelection:allowPublic + ~schemaState ~env ~attributeLoc:name.loc payload with | None -> declared | Some fn -> {declared with functions = declared.functions @ [fn]}) @@ -1311,7 +1371,7 @@ type persistedLegacySchemaState = { } let stateFileMagic = "RESGRAPH_STATE\000" -let stateFileVersion = 1 +let stateFileVersion = 2 let validStateName schemaName = Str.string_match (Str.regexp "^[A-Za-z0-9_-]+$") schemaName 0 diff --git a/src/res/ResGraph.res b/src/res/ResGraph.res index d5a0165e..ee2e9bfd 100644 --- a/src/res/ResGraph.res +++ b/src/res/ResGraph.res @@ -16,6 +16,9 @@ module Connections = ResGraph__Connections module Utils = ResGraph__Utils module Authorization = { + type coverage = Selection + type coverageOptions = {covers: coverage} + type outcome<'value, 'reason> = | Allowed('value) | Forbidden('reason) diff --git a/tests/authorization/baseline/src/ResGraph.res b/tests/authorization/baseline/src/ResGraph.res index 72b9c403..be234fbe 100644 --- a/tests/authorization/baseline/src/ResGraph.res +++ b/tests/authorization/baseline/src/ResGraph.res @@ -1,6 +1,9 @@ type resolveInfo = unit module Authorization = { + type coverage = Selection + type coverageOptions = {covers: coverage} + type outcome<'value, 'reason> = | Allowed('value) | Forbidden('reason) diff --git a/tests/authorization/invalid/src/Query.res b/tests/authorization/invalid/src/Query.res index de55adcb..046ac550 100644 --- a/tests/authorization/invalid/src/Query.res +++ b/tests/authorization/invalid/src/Query.res @@ -1,4 +1,6 @@ -@gql.public({reason: "Types cannot be public"}) @gql.type +@gql.public({reason: "Types cannot be public"}) +@gql.authorize((Security.good, {ResGraph.Authorization.covers: Selection})) +@gql.type type query @gql.field @@ -39,3 +41,18 @@ let badContext = (_: query): string => "bad context" @gql.authorize(Security.nonUnitOutcome) @gql.field let nonUnitOutcome = (_: query): string => "bad outcome" + +@gql.type +type sharedSelection = { + @gql.field + value: string, +} + +@gql.authorize( + (Security.canSelect, {ResGraph.Authorization.covers: Selection}) +) +@gql.field +let protectedSelection = (_: query): sharedSelection => {value: "protected"} + +@gql.public({reason: "Intentionally exercises an unprotected alternate path"}) @gql.field +let publicSelection = (_: query): sharedSelection => {value: "public"} diff --git a/tests/authorization/invalid/src/ResGraph.res b/tests/authorization/invalid/src/ResGraph.res index 97ecee76..f65d86bb 100644 --- a/tests/authorization/invalid/src/ResGraph.res +++ b/tests/authorization/invalid/src/ResGraph.res @@ -1,4 +1,7 @@ type resolveInfo = unit module Authorization = { + type coverage = Selection + type coverageOptions = {covers: coverage} + type outcome<'value, 'reason> = Allowed('value) | Forbidden('reason) } diff --git a/tests/authorization/invalid/src/Security.res b/tests/authorization/invalid/src/Security.res index d997be59..216d4b09 100644 --- a/tests/authorization/invalid/src/Security.res +++ b/tests/authorization/invalid/src/Security.res @@ -53,3 +53,5 @@ let nonUnitOutcome = (_: Query.query, ~args: {.}): ResGraph.Authorization.outcom string, reason, > => ResGraph.Authorization.Allowed("wrong") + +let canSelect = (_: Query.query, ~args: {.}) => ResGraph.Authorization.Allowed() diff --git a/tests/authorization/run-tests.sh b/tests/authorization/run-tests.sh index 9200f7d6..91fe79ef 100755 --- a/tests/authorization/run-tests.sh +++ b/tests/authorization/run-tests.sh @@ -58,9 +58,26 @@ grep -F 'ResGraph.Authorization.raiseError(Security.onForbidden(reason, ~ctx=ctx grep -F 'switch Security.canReadNamed(Obj.magic(src)' "$tmp_dir/valid/ResGraphSchema.res" >/dev/null grep -F 'switch Security.first' "$tmp_dir/valid/ResGraphSchema.res" >/dev/null grep -F 'switch Security.Alias.second' "$tmp_dir/valid/ResGraphSchema.res" >/dev/null +if [[ "$(grep -c 'switch Security.canLoadSelection' "$tmp_dir/valid/ResGraphSchema.res")" -ne 1 ]]; then + echo "Selection policy was not emitted exactly once at its boundary." >&2 + exit 1 +fi diff -u "$root_dir/tests/authorization/valid/expected-authorization-manifest.json" \ "$tmp_dir/valid/authorization-manifest.json" +mkdir -p "$tmp_dir/manifest-upgrade" +cp "$root_dir/tests/authorization/valid/expected-authorization-manifest.json" \ + "$tmp_dir/manifest-upgrade/authorization-manifest.json" +sed -i 's/"version": 2/"version": 1/' \ + "$tmp_dir/manifest-upgrade/authorization-manifest.json" +"$resgraph_bin" generate-schema \ + "$root_dir/tests/authorization/valid/src" \ + "$tmp_dir/manifest-upgrade" false required Security.onForbidden \ + "$tmp_dir/manifest-upgrade/authorization-manifest.json" \ + >"$tmp_dir/manifest-upgrade-result.json" +jq -e '.generatedBy == "resgraph" and .version == 2 and .status == "success"' \ + "$tmp_dir/manifest-upgrade/authorization-manifest.json" >/dev/null + mkdir -p "$tmp_dir/cache-bypass" "$resgraph_bin" generate-schema \ "$root_dir/tests/authorization/invalid/src" \ @@ -106,6 +123,10 @@ grep -F 'has source type `Mutation`, but it is applied to `Query`' \ grep -F 'must declare `~args` as a ReScript polymorphic object' \ "$tmp_dir/invalid-result.json" >/dev/null grep -F 'has invalid `~ctx`' "$tmp_dir/invalid-result.json" >/dev/null +grep -F '`@gql.authorize((..., {covers: Selection}))` can only be used on output fields' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Field `SharedSelection.value` has no authorization disposition.' \ + "$tmp_dir/invalid-result.json" >/dev/null grep -F 'Required authorization coverage does not support subscription field `Subscription.events` yet.' \ "$tmp_dir/invalid-result.json" >/dev/null diff --git a/tests/authorization/valid/expected-authorization-manifest.json b/tests/authorization/valid/expected-authorization-manifest.json index ddb8bd52..0dcf4551 100644 --- a/tests/authorization/valid/expected-authorization-manifest.json +++ b/tests/authorization/valid/expected-authorization-manifest.json @@ -1,6 +1,6 @@ { "generatedBy": "resgraph", - "version": 1, + "version": 2, "status": "success", "fields": [ {"coordinate":"DeclaredResultFailure.message","disposition":"synthetic","mutation":false,"policies":[],"public":null,"resolverOutcome":null}, @@ -30,7 +30,12 @@ {"coordinate":"Query.outcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":false}}, {"coordinate":"Query.outcomeDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadOutcomeDevice","provenance":"field:Query.outcomeDevice","file":"src/Query.res","location":"[38:0->38:14]","async":false}],"public":null,"resolverOutcome":null}, {"coordinate":"Query.publicDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadPublicDevice","provenance":"field:Query.publicDevice","file":"src/Query.res","location":"[35:0->35:14]","async":false}],"public":null,"resolverOutcome":null}, + {"coordinate":"Query.selection","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"covers":"selection"}],"public":null,"resolverOutcome":null}, {"coordinate":"Query.user","disposition":"policies","mutation":false,"policies":[{"path":"Security.canFindUser","provenance":"field:Query.user","file":"src/Query.res","location":"[8:0->8:14]","async":false}],"public":null,"resolverOutcome":null}, + {"coordinate":"SelectionConnection.edges","disposition":"selection","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"selectionCoverage":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"covers":"selection"}}]}, + {"coordinate":"SelectionEdge.cursor","disposition":"selection","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"selectionCoverage":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"covers":"selection"}}]}, + {"coordinate":"SelectionEdge.node","disposition":"selection","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"selectionCoverage":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"covers":"selection"}}]}, + {"coordinate":"SelectionNode.value","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadSelectionNode","provenance":"objectType:SelectionNode","file":"src/SelectionCoverage.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null,"selectionCoverage":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"covers":"selection"}}]}, {"coordinate":"User.id","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null}, {"coordinate":"User.secret","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:2->4:16]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:39->4:53]","async":false}],"public":null,"resolverOutcome":null} ] diff --git a/tests/authorization/valid/src/Query.res b/tests/authorization/valid/src/Query.res index d5680c4b..9c007f2f 100644 --- a/tests/authorization/valid/src/Query.res +++ b/tests/authorization/valid/src/Query.res @@ -44,3 +44,11 @@ type declaredResult = Success({value: string}) | Failure({message: string}) @gql.authorize(Security.first) @gql.field let declared = (_: query): declaredResult => Success({value: "visible"}) + +@gql.authorize( + (Security.canLoadSelection, {ResGraph.Authorization.covers: Selection}) +) +@gql.field +let selection = (_: query): SelectionCoverage.selectionConnection => { + edges: [{cursor: "cursor", node: {value: "selected"}}], +} diff --git a/tests/authorization/valid/src/ResGraph.res b/tests/authorization/valid/src/ResGraph.res index 72b9c403..be234fbe 100644 --- a/tests/authorization/valid/src/ResGraph.res +++ b/tests/authorization/valid/src/ResGraph.res @@ -1,6 +1,9 @@ type resolveInfo = unit module Authorization = { + type coverage = Selection + type coverageOptions = {covers: coverage} + type outcome<'value, 'reason> = | Allowed('value) | Forbidden('reason) diff --git a/tests/authorization/valid/src/Security.res b/tests/authorization/valid/src/Security.res index 4a783bdd..d053585f 100644 --- a/tests/authorization/valid/src/Security.res +++ b/tests/authorization/valid/src/Security.res @@ -40,3 +40,8 @@ module Alias = Nested let canLoadPublicDevice = (_: Query.query, ~args) => ResGraph.Authorization.Allowed() let canLoadOutcomeDevice = (_: Query.query, ~args) => ResGraph.Authorization.Allowed() + +let canLoadSelection = (_: Query.query, ~args) => ResGraph.Authorization.Allowed() + +let canReadSelectionNode = (_: SelectionCoverage.selectionNode, ~args) => + ResGraph.Authorization.Allowed() diff --git a/tests/authorization/valid/src/SelectionCoverage.res b/tests/authorization/valid/src/SelectionCoverage.res new file mode 100644 index 00000000..4d857a97 --- /dev/null +++ b/tests/authorization/valid/src/SelectionCoverage.res @@ -0,0 +1,20 @@ +@gql.authorize(Security.canReadSelectionNode) +@gql.type +type selectionNode = { + @gql.field + value: string, +} + +@gql.type +type selectionEdge = { + @gql.field + cursor: string, + @gql.field + node: selectionNode, +} + +@gql.type +type selectionConnection = { + @gql.field + edges: array, +} From b0412a240e242074693783a71c5c1cfb937f757a Mon Sep 17 00:00:00 2001 From: Gabriel Nordeborn Date: Sat, 1 Aug 2026 23:31:48 +0200 Subject: [PATCH 2/6] Refine authorization scope API --- CHANGELOG.md | 4 +- docs/docs/authorization.md | 34 ++++---- src/ml/GenerateSchemaAuthorization.ml | 80 +++++++++---------- src/ml/GenerateSchemaTypePrinters.ml | 2 +- src/ml/GenerateSchemaTypes.ml | 8 +- src/ml/GenerateSchemaUtils.ml | 40 +++++----- src/res/ResGraph.res | 4 +- tests/authorization/baseline/src/ResGraph.res | 4 +- tests/authorization/invalid/src/Query.res | 4 +- tests/authorization/invalid/src/ResGraph.res | 4 +- tests/authorization/run-tests.sh | 4 +- .../expected-authorization-manifest.json | 10 +-- tests/authorization/valid/src/Query.res | 2 +- tests/authorization/valid/src/ResGraph.res | 4 +- 14 files changed, 99 insertions(+), 105 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a4d1e8ed..ada49731 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,8 @@ ## Unreleased -- Allow field authorization policies to cover their returned selection with - `{covers: Selection}`, including statically validated path coverage and +- Allow field authorization policies to include their returned fields with + `{scope: Fields}`, including statically validated path coverage and authorization-manifest provenance without repeated policy evaluation. ## 1.3.0 diff --git a/docs/docs/authorization.md b/docs/docs/authorization.md index 7307dd8d..e0bdd25f 100644 --- a/docs/docs/authorization.md +++ b/docs/docs/authorization.md @@ -88,16 +88,16 @@ Type, interface, field, and resolver policies compose additively. Interface fiel By default, a policy on a field returning an object does not authorize that object's child fields. Each output field needs its own disposition. -### Covering a returned selection +### Scoping authorization to returned fields -A field policy can explicitly cover the selection returned beneath that field. -This is useful for connection wrappers, mutation payloads, and calculated result -objects that have no authorization identity independent of the field producing -them: +A field policy can explicitly include the fields returned beneath that field in +its authorization scope. This is useful for connection wrappers, mutation +payloads, and calculated result objects that have no authorization identity +independent of the field producing them: ```rescript @gql.authorize( - (CampaignSecurity.canList, {ResGraph.Authorization.covers: Selection}) + (CampaignSecurity.canList, {scope: Fields}) ) @gql.field let campaigns = async ( @@ -110,19 +110,19 @@ let campaigns = async ( ``` The inner parentheses form the ReScript tuple consumed by `@gql.authorize`. -The qualified record label gives ReScript the configuration type, from which it -infers and checks the `Selection` constructor. +ReScript infers the scope record from the regular `Fields` constructor, so +neither the record label nor constructor needs qualification. The policy runs once on `Query.campaigns`. Required authorization treats fields -reachable exclusively beneath that result as selection-covered, without -generating additional policy calls for them. Local type and field policies -still run and compose additively when present. +reachable exclusively beneath that result as within its scope, without +generating additional policy calls for them. Local type and field policies still +run and compose additively when present. -Selection coverage is path-sensitive. If the same result type is also reachable -through a path without a selection-covering policy, its otherwise-uncovered -fields fail required authorization. Public fields and resolver outcomes do not -establish selection coverage. `covers: Selection` is supported only on output -fields and resolver functions, not on type policies. +Field scope is path-sensitive. If the same result type is also reachable through +a path without a `scope: Fields` policy, its otherwise-uncovered fields fail +required authorization. Public fields and resolver outcomes do not widen a +policy's scope. `scope: Fields` is supported only on output fields and resolver +functions, not on type policies. ## Resolver outcomes @@ -174,7 +174,7 @@ let onForbidden = ( ## Audit manifest and boundaries -`manifestPath` emits stable, sorted JSON with every concrete field, its disposition, policy order and provenance, inherited selection boundaries, public reason, source locations, resolver-outcome metadata, and mutation status. For a field reachable through multiple covered paths, `selectionCoverage` lists the possible boundary sources; only the boundary on the selected runtime path executes. Commit the manifest when authorization posture should be reviewed through diffs. +`manifestPath` emits stable, sorted JSON with every concrete field, its disposition, policy order and provenance, inherited scope boundaries, public reason, source locations, resolver-outcome metadata, and mutation status. For a field reachable through multiple scoped paths, `scopeBoundaries` lists the possible boundary sources; only the boundary on the selected runtime path executes. Commit the manifest when authorization posture should be reviewed through diffs. Fields on inferred union payload objects use the `synthetic` disposition. They have no annotation surface and are reachable only after their parent resolver diff --git a/src/ml/GenerateSchemaAuthorization.ml b/src/ml/GenerateSchemaAuthorization.ml index c154f32f..b388002c 100644 --- a/src/ml/GenerateSchemaAuthorization.ml +++ b/src/ml/GenerateSchemaAuthorization.ml @@ -394,7 +394,7 @@ let loadBaseline path = BaselineEntries.empty let gapForField ~(typ : gqlObjectType) ~(field : gqlField) ~synthetic ~public - ~references ~inheritedSelectionPolicies ~resolverOutcome = + ~references ~inheritedScopePolicies ~resolverOutcome = let coordinate = GenerateSchemaUtils.authorizationCoordinate ~parentTypeName:typ.displayName ~fieldName:field.name @@ -403,7 +403,7 @@ let gapForField ~(typ : gqlObjectType) ~(field : gqlField) ~synthetic ~public else if synthetic then None else if Option.is_none public && references = [] - && inheritedSelectionPolicies = [] + && inheritedScopePolicies = [] && Option.is_none resolverOutcome then Some (coordinate, UncoveredField) else if typ.id = "mutation" && Option.is_none public && references = [] then @@ -498,24 +498,24 @@ let buildFieldPlan ~loader ~package ~(schemaState : schemaState) Hashtbl.replace schemaState.authorizationPlans coordinate { functions; - inheritedSelectionPolicies = []; + inheritedScopePolicies = []; public; resolverOutcome; synthetic; baselineGap = None; } -module InheritedSelectionPolicy = struct - type t = inheritedSelectionPolicy +module InheritedScopePolicy = struct + type t = inheritedScopePolicy let compare = Stdlib.compare end -module InheritedSelectionPolicies = Set.Make (InheritedSelectionPolicy) +module InheritedScopePolicies = Set.Make (InheritedScopePolicy) -type selectionReachability = { +type scopeReachability = { hasUnprotectedPath: bool; - policies: InheritedSelectionPolicies.t; + policies: InheritedScopePolicies.t; } let rec outputTypeIds ~processedSchema = function @@ -555,13 +555,13 @@ let fieldOutputTypeIds ~processedSchema (schemaState : schemaState) in ids field.typ |> List.sort_uniq String.compare -let selectionPolicies coordinate (plan : effectiveAuthorizationPlan) = +let scopePolicies coordinate (plan : effectiveAuthorizationPlan) = plan.functions |> List.filter_map (fun (fn : authorizationFunction) -> - match fn.reference.covers with + match fn.reference.scope with | AuthorizationField -> None - | AuthorizationSelection -> Some {boundaryCoordinate = coordinate; fn}) - |> InheritedSelectionPolicies.of_list + | AuthorizationFields -> Some {boundaryCoordinate = coordinate; fn}) + |> InheritedScopePolicies.of_list let updateReachability reachability typeId incoming = match Hashtbl.find_opt reachability typeId with @@ -574,7 +574,7 @@ let updateReachability reachability typeId incoming = hasUnprotectedPath = existing.hasUnprotectedPath || incoming.hasUnprotectedPath; policies = - InheritedSelectionPolicies.union existing.policies incoming.policies; + InheritedScopePolicies.union existing.policies incoming.policies; } in if merged = existing then false @@ -582,7 +582,7 @@ let updateReachability reachability typeId incoming = Hashtbl.replace reachability typeId merged; true) -let selectionReachability ~processedSchema (schemaState : schemaState) = +let scopeReachability ~processedSchema (schemaState : schemaState) = let reachability = Hashtbl.create 50 in let pending = Queue.create () in let enqueueRoot = function @@ -590,10 +590,7 @@ let selectionReachability ~processedSchema (schemaState : schemaState) = | Some (typ : gqlObjectType) -> if updateReachability reachability typ.id - { - hasUnprotectedPath = true; - policies = InheritedSelectionPolicies.empty; - } + {hasUnprotectedPath = true; policies = InheritedScopePolicies.empty} then Queue.add typ.id pending in enqueueRoot schemaState.query; @@ -613,14 +610,14 @@ let selectionReachability ~processedSchema (schemaState : schemaState) = ~parentTypeName:typ.displayName ~fieldName:field.name in let plan = Hashtbl.find schemaState.authorizationPlans coordinate in - let localPolicies = selectionPolicies coordinate plan in + let localPolicies = scopePolicies coordinate plan in let outgoing = { hasUnprotectedPath = incoming.hasUnprotectedPath - && InheritedSelectionPolicies.is_empty localPolicies; + && InheritedScopePolicies.is_empty localPolicies; policies = - InheritedSelectionPolicies.union incoming.policies localPolicies; + InheritedScopePolicies.union incoming.policies localPolicies; } in fieldOutputTypeIds ~processedSchema schemaState field @@ -631,16 +628,15 @@ let selectionReachability ~processedSchema (schemaState : schemaState) = done; reachability -let applyInheritedSelectionPolicies ~processedSchema (schemaState : schemaState) - = - let reachability = selectionReachability ~processedSchema schemaState in +let applyInheritedScopePolicies ~processedSchema (schemaState : schemaState) = + let reachability = scopeReachability ~processedSchema schemaState in schemaState.types |> Hashtbl.iter (fun typeId (typ : gqlObjectType) -> - let inheritedSelectionPolicies = + let inheritedScopePolicies = match Hashtbl.find_opt reachability typeId with | Some {hasUnprotectedPath = false; policies} - when not (InheritedSelectionPolicies.is_empty policies) -> - InheritedSelectionPolicies.elements policies + when not (InheritedScopePolicies.is_empty policies) -> + InheritedScopePolicies.elements policies | _ -> [] in typ.fields @@ -653,7 +649,7 @@ let applyInheritedSelectionPolicies ~processedSchema (schemaState : schemaState) | None -> () | Some plan -> Hashtbl.replace schemaState.authorizationPlans coordinate - {plan with inheritedSelectionPolicies})) + {plan with inheritedScopePolicies})) let finalizeFieldPlan ~(schemaState : schemaState) ~baselineEntries ~skipGapDiagnostics ~(typ : gqlObjectType) ~(field : gqlField) = @@ -668,7 +664,7 @@ let finalizeFieldPlan ~(schemaState : schemaState) ~baselineEntries in let gap = gapForField ~typ ~field ~synthetic:plan.synthetic ~public:plan.public - ~references ~inheritedSelectionPolicies:plan.inheritedSelectionPolicies + ~references ~inheritedScopePolicies:plan.inheritedScopePolicies ~resolverOutcome:plan.resolverOutcome in let baselineGap = @@ -733,7 +729,7 @@ let buildPlans ~loader ~package ~processedSchema (schemaState : schemaState) = typ.fields |> List.iter (fun field -> buildFieldPlan ~loader ~package ~schemaState ~typ ~field)); - applyInheritedSelectionPolicies ~processedSchema schemaState; + applyInheritedScopePolicies ~processedSchema schemaState; schemaState.types |> GenerateSchemaUtils.iterHashtblAlphabetically (fun _ (typ : gqlObjectType) -> @@ -763,10 +759,10 @@ let provenanceToString = function | FieldPolicy coordinate -> "field:" ^ coordinate let manifestPolicy ~package (fn : authorizationFunction) = - let covers = - match fn.reference.covers with + let scope = + match fn.reference.scope with | AuthorizationField -> "" - | AuthorizationSelection -> ",\"covers\":\"selection\"" + | AuthorizationFields -> ",\"scope\":\"fields\"" in Printf.sprintf "{\"path\":%s,\"provenance\":%s,\"file\":%s,\"location\":%s,\"async\":%s%s}" @@ -775,9 +771,9 @@ let manifestPolicy ~package (fn : authorizationFunction) = (jsonString (relativeSourcePath ~package fn.reference.fileUri)) (jsonString (Loc.toString fn.reference.loc)) (if fn.isAsync then "true" else "false") - covers + scope -let manifestInheritedPolicy ~package (policy : inheritedSelectionPolicy) = +let manifestScopeBoundary ~package (policy : inheritedScopePolicy) = Printf.sprintf "{\"boundary\":%s,\"policy\":%s}" (jsonString policy.boundaryCoordinate) (manifestPolicy ~package policy.fn) @@ -789,7 +785,7 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = plan.synthetic, plan.public, plan.functions, - plan.inheritedSelectionPolicies, + plan.inheritedScopePolicies, plan.resolverOutcome ) with | Some _, _, _, _, _, _ -> "baseline" @@ -797,7 +793,7 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = | None, false, Some _, _, _, _ -> "public" | None, false, None, _ :: _, _, _ -> "policies" | None, false, None, [], _, Some _ -> "resolverOutcome" - | None, false, None, [], _ :: _, None -> "selection" + | None, false, None, [], _ :: _, None -> "scope" | None, false, None, [], [], None -> "uncovered" in let publicJson = @@ -815,13 +811,13 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = | Some {isAsync} -> Printf.sprintf "{\"async\":%s}" (if isAsync then "true" else "false") in - let inheritedSelectionJson = - match plan.inheritedSelectionPolicies with + let inheritedScopeJson = + match plan.inheritedScopePolicies with | [] -> "" | policies -> - Printf.sprintf ",\"selectionCoverage\":[%s]" + Printf.sprintf ",\"scopeBoundaries\":[%s]" (policies - |> List.map (manifestInheritedPolicy ~package) + |> List.map (manifestScopeBoundary ~package) |> String.concat ",") in Printf.sprintf @@ -830,7 +826,7 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = (if String.starts_with coordinate ~prefix:"Mutation." then "true" else "false") (plan.functions |> List.map (manifestPolicy ~package) |> String.concat ",") - publicJson resolverOutcomeJson inheritedSelectionJson + publicJson resolverOutcomeJson inheritedScopeJson let rec ensureDirectory path = if path = "" || path = "." || Sys.file_exists path then () diff --git a/src/ml/GenerateSchemaTypePrinters.ml b/src/ml/GenerateSchemaTypePrinters.ml index 62a9ac65..6d4a3b8b 100644 --- a/src/ml/GenerateSchemaTypePrinters.ml +++ b/src/ml/GenerateSchemaTypePrinters.ml @@ -47,7 +47,7 @@ let printResolverForField ~parentTypeName ~(schemaState : schemaState) | None -> { functions = []; - inheritedSelectionPolicies = []; + inheritedScopePolicies = []; public = None; resolverOutcome = Hashtbl.find_opt schemaState.resolverOutcomes coordinate; diff --git a/src/ml/GenerateSchemaTypes.ml b/src/ml/GenerateSchemaTypes.ml index d4e862ae..c68d954b 100644 --- a/src/ml/GenerateSchemaTypes.ml +++ b/src/ml/GenerateSchemaTypes.ml @@ -39,13 +39,13 @@ type authorizationConfig = { baselinePath: string option; } -type authorizationCoverage = AuthorizationField | AuthorizationSelection +type authorizationScope = AuthorizationField | AuthorizationFields type authorizationFunctionReference = { path: string list; loc: Location.t; fileUri: Uri.t; - covers: authorizationCoverage; + scope: authorizationScope; } type publicAuthorization = {reason: string; loc: Location.t; fileUri: Uri.t} @@ -79,14 +79,14 @@ type authorizationGapKind = type effectiveAuthorizationPlan = { functions: authorizationFunction list; - inheritedSelectionPolicies: inheritedSelectionPolicy list; + inheritedScopePolicies: inheritedScopePolicy list; public: publicAuthorization option; resolverOutcome: resolverOutcome option; synthetic: bool; baselineGap: authorizationGapKind option; } -and inheritedSelectionPolicy = { +and inheritedScopePolicy = { boundaryCoordinate: string; fn: authorizationFunction; } diff --git a/src/ml/GenerateSchemaUtils.ml b/src/ml/GenerateSchemaUtils.ml index 947ecb93..51382173 100644 --- a/src/ml/GenerateSchemaUtils.ml +++ b/src/ml/GenerateSchemaUtils.ml @@ -162,52 +162,50 @@ let addAuthorizationDiagnostic ~schemaState ~(env : SharedTypes.QueryEnv.t) ~loc |> addDiagnostic ~diagnostic:{loc; fileUri = env.SharedTypes.QueryEnv.file.uri; message} -let authorizationCoverageFromRecord ~schemaState ~(env : SharedTypes.QueryEnv.t) +let authorizationScopeFromRecord ~schemaState ~(env : SharedTypes.QueryEnv.t) ~attributeLoc fields = - let coversFields = + let scopeFields = fields |> List.filter (fun (field : Parsetree.expression Parsetree.record_element) -> - Longident.last field.lid.txt = "covers") + Longident.last field.lid.txt = "scope") in - match (fields, coversFields) with + match (fields, scopeFields) with | [_], [field] -> ( match field.x.pexp_desc with | Pexp_construct ({txt = constructor}, None) - when Longident.last constructor = "Selection" -> - Some AuthorizationSelection + when Longident.last constructor = "Fields" -> + Some AuthorizationFields | _ -> addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.authorize` coverage must be the `Selection` constructor, for \ - example `@gql.authorize((Security.canRead, \ - {ResGraph.Authorization.covers: Selection}))`."; + "`@gql.authorize` scope must be the `Fields` constructor, for example \ + `@gql.authorize((Security.canRead, {scope: Fields}))`."; None) | [], _ | _, [] -> addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.authorize` coverage requires `{covers: Selection}` in its tuple \ - payload."; + "`@gql.authorize` scope requires `{scope: Fields}` in its tuple payload."; None | _ -> addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.authorize` coverage accepts only `{covers: Selection}`."; + "`@gql.authorize` scope accepts only `{scope: Fields}`."; None -let functionReferenceFromPayload ~allowSelection ~schemaState +let functionReferenceFromPayload ~allowFieldsScope ~schemaState ~(env : SharedTypes.QueryEnv.t) ~attributeLoc (payload : Parsetree.payload) = - let reference functionPath covers = + let reference functionPath scope = let path = Longident.flatten functionPath in if List.length path < 2 then ( addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc "`@gql.authorize` requires a module-qualified function path, for \ example `Security.canRead`."; None) - else if covers = AuthorizationSelection && not allowSelection then ( + else if scope = AuthorizationFields && not allowFieldsScope then ( addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.authorize((..., {covers: Selection}))` can only be used on \ - output fields or resolver functions, not on a type."; + "`@gql.authorize((..., {scope: Fields}))` can only be used on output \ + fields or resolver functions, not on a type."; None) - else Some {path; loc = attributeLoc; fileUri = env.file.uri; covers} + else Some {path; loc = attributeLoc; fileUri = env.file.uri; scope} in match payload with | PStr @@ -235,10 +233,10 @@ let functionReferenceFromPayload ~allowSelection ~schemaState }; ] -> ( match - authorizationCoverageFromRecord ~schemaState ~env ~attributeLoc fields + authorizationScopeFromRecord ~schemaState ~env ~attributeLoc fields with | None -> None - | Some covers -> reference functionPath covers) + | Some scope -> reference functionPath scope) | _ -> addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc "`@gql.authorize` requires a module-qualified function path, for example \ @@ -289,7 +287,7 @@ let extractDeclaredAuthorization ~allowPublic ~schemaState match String.split_on_char '.' name.txt with | ["gql"; "authorize"] -> ( match - functionReferenceFromPayload ~allowSelection:allowPublic + functionReferenceFromPayload ~allowFieldsScope:allowPublic ~schemaState ~env ~attributeLoc:name.loc payload with | None -> declared diff --git a/src/res/ResGraph.res b/src/res/ResGraph.res index ee2e9bfd..18cd348f 100644 --- a/src/res/ResGraph.res +++ b/src/res/ResGraph.res @@ -16,8 +16,8 @@ module Connections = ResGraph__Connections module Utils = ResGraph__Utils module Authorization = { - type coverage = Selection - type coverageOptions = {covers: coverage} + type scope = Fields + type scopeOptions = {scope: scope} type outcome<'value, 'reason> = | Allowed('value) diff --git a/tests/authorization/baseline/src/ResGraph.res b/tests/authorization/baseline/src/ResGraph.res index be234fbe..18f4644f 100644 --- a/tests/authorization/baseline/src/ResGraph.res +++ b/tests/authorization/baseline/src/ResGraph.res @@ -1,8 +1,8 @@ type resolveInfo = unit module Authorization = { - type coverage = Selection - type coverageOptions = {covers: coverage} + type scope = Fields + type scopeOptions = {scope: scope} type outcome<'value, 'reason> = | Allowed('value) diff --git a/tests/authorization/invalid/src/Query.res b/tests/authorization/invalid/src/Query.res index 046ac550..b89fa3bd 100644 --- a/tests/authorization/invalid/src/Query.res +++ b/tests/authorization/invalid/src/Query.res @@ -1,5 +1,5 @@ @gql.public({reason: "Types cannot be public"}) -@gql.authorize((Security.good, {ResGraph.Authorization.covers: Selection})) +@gql.authorize((Security.good, {scope: Fields})) @gql.type type query @@ -49,7 +49,7 @@ type sharedSelection = { } @gql.authorize( - (Security.canSelect, {ResGraph.Authorization.covers: Selection}) + (Security.canSelect, {scope: Fields}) ) @gql.field let protectedSelection = (_: query): sharedSelection => {value: "protected"} diff --git a/tests/authorization/invalid/src/ResGraph.res b/tests/authorization/invalid/src/ResGraph.res index f65d86bb..b8b45314 100644 --- a/tests/authorization/invalid/src/ResGraph.res +++ b/tests/authorization/invalid/src/ResGraph.res @@ -1,7 +1,7 @@ type resolveInfo = unit module Authorization = { - type coverage = Selection - type coverageOptions = {covers: coverage} + type scope = Fields + type scopeOptions = {scope: scope} type outcome<'value, 'reason> = Allowed('value) | Forbidden('reason) } diff --git a/tests/authorization/run-tests.sh b/tests/authorization/run-tests.sh index 91fe79ef..67674d6f 100755 --- a/tests/authorization/run-tests.sh +++ b/tests/authorization/run-tests.sh @@ -59,7 +59,7 @@ grep -F 'switch Security.canReadNamed(Obj.magic(src)' "$tmp_dir/valid/ResGraphSc grep -F 'switch Security.first' "$tmp_dir/valid/ResGraphSchema.res" >/dev/null grep -F 'switch Security.Alias.second' "$tmp_dir/valid/ResGraphSchema.res" >/dev/null if [[ "$(grep -c 'switch Security.canLoadSelection' "$tmp_dir/valid/ResGraphSchema.res")" -ne 1 ]]; then - echo "Selection policy was not emitted exactly once at its boundary." >&2 + echo "Fields-scoped policy was not emitted exactly once at its boundary." >&2 exit 1 fi diff -u "$root_dir/tests/authorization/valid/expected-authorization-manifest.json" \ @@ -123,7 +123,7 @@ grep -F 'has source type `Mutation`, but it is applied to `Query`' \ grep -F 'must declare `~args` as a ReScript polymorphic object' \ "$tmp_dir/invalid-result.json" >/dev/null grep -F 'has invalid `~ctx`' "$tmp_dir/invalid-result.json" >/dev/null -grep -F '`@gql.authorize((..., {covers: Selection}))` can only be used on output fields' \ +grep -F '`@gql.authorize((..., {scope: Fields}))` can only be used on output fields' \ "$tmp_dir/invalid-result.json" >/dev/null grep -F 'Field `SharedSelection.value` has no authorization disposition.' \ "$tmp_dir/invalid-result.json" >/dev/null diff --git a/tests/authorization/valid/expected-authorization-manifest.json b/tests/authorization/valid/expected-authorization-manifest.json index 0dcf4551..1591d51f 100644 --- a/tests/authorization/valid/expected-authorization-manifest.json +++ b/tests/authorization/valid/expected-authorization-manifest.json @@ -30,12 +30,12 @@ {"coordinate":"Query.outcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":false}}, {"coordinate":"Query.outcomeDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadOutcomeDevice","provenance":"field:Query.outcomeDevice","file":"src/Query.res","location":"[38:0->38:14]","async":false}],"public":null,"resolverOutcome":null}, {"coordinate":"Query.publicDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadPublicDevice","provenance":"field:Query.publicDevice","file":"src/Query.res","location":"[35:0->35:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.selection","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"covers":"selection"}],"public":null,"resolverOutcome":null}, + {"coordinate":"Query.selection","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"scope":"fields"}],"public":null,"resolverOutcome":null}, {"coordinate":"Query.user","disposition":"policies","mutation":false,"policies":[{"path":"Security.canFindUser","provenance":"field:Query.user","file":"src/Query.res","location":"[8:0->8:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"SelectionConnection.edges","disposition":"selection","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"selectionCoverage":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"covers":"selection"}}]}, - {"coordinate":"SelectionEdge.cursor","disposition":"selection","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"selectionCoverage":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"covers":"selection"}}]}, - {"coordinate":"SelectionEdge.node","disposition":"selection","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"selectionCoverage":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"covers":"selection"}}]}, - {"coordinate":"SelectionNode.value","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadSelectionNode","provenance":"objectType:SelectionNode","file":"src/SelectionCoverage.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null,"selectionCoverage":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"covers":"selection"}}]}, + {"coordinate":"SelectionConnection.edges","disposition":"scope","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"scopeBoundaries":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"scope":"fields"}}]}, + {"coordinate":"SelectionEdge.cursor","disposition":"scope","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"scopeBoundaries":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"scope":"fields"}}]}, + {"coordinate":"SelectionEdge.node","disposition":"scope","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"scopeBoundaries":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"scope":"fields"}}]}, + {"coordinate":"SelectionNode.value","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadSelectionNode","provenance":"objectType:SelectionNode","file":"src/SelectionCoverage.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null,"scopeBoundaries":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"scope":"fields"}}]}, {"coordinate":"User.id","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null}, {"coordinate":"User.secret","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:2->4:16]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:39->4:53]","async":false}],"public":null,"resolverOutcome":null} ] diff --git a/tests/authorization/valid/src/Query.res b/tests/authorization/valid/src/Query.res index 9c007f2f..7120ba16 100644 --- a/tests/authorization/valid/src/Query.res +++ b/tests/authorization/valid/src/Query.res @@ -46,7 +46,7 @@ type declaredResult = Success({value: string}) | Failure({message: string}) let declared = (_: query): declaredResult => Success({value: "visible"}) @gql.authorize( - (Security.canLoadSelection, {ResGraph.Authorization.covers: Selection}) + (Security.canLoadSelection, {scope: Fields}) ) @gql.field let selection = (_: query): SelectionCoverage.selectionConnection => { diff --git a/tests/authorization/valid/src/ResGraph.res b/tests/authorization/valid/src/ResGraph.res index be234fbe..18f4644f 100644 --- a/tests/authorization/valid/src/ResGraph.res +++ b/tests/authorization/valid/src/ResGraph.res @@ -1,8 +1,8 @@ type resolveInfo = unit module Authorization = { - type coverage = Selection - type coverageOptions = {covers: coverage} + type scope = Fields + type scopeOptions = {scope: scope} type outcome<'value, 'reason> = | Allowed('value) From 7726536bfb842cc305b3fb4e92a56f955748bbfb Mon Sep 17 00:00:00 2001 From: Gabriel Nordeborn Date: Sun, 2 Aug 2026 18:54:42 +0200 Subject: [PATCH 3/6] Replace authorization scopes with ancestor assertions --- CHANGELOG.md | 6 +- docs/docs/authorization.md | 60 +++-- src/ml/GenerateSchemaAuthorization.ml | 220 +++++++++++++----- src/ml/GenerateSchemaTypePrinters.ml | 3 +- src/ml/GenerateSchemaTypes.ml | 19 +- src/ml/GenerateSchemaUtils.ml | 186 +++++++-------- src/res/ResGraph.res | 3 - tests/authorization/baseline/src/ResGraph.res | 3 - tests/authorization/invalid/src/Query.res | 26 ++- tests/authorization/invalid/src/ResGraph.res | 3 - .../invalid/src/UnsupportedInterface.res | 11 + tests/authorization/run-tests.sh | 31 ++- .../expected-authorization-manifest.json | 81 ++++--- .../authorization/valid/src/AncestorGraph.res | 32 +++ tests/authorization/valid/src/Mutation.res | 9 +- tests/authorization/valid/src/Query.res | 14 +- tests/authorization/valid/src/ResGraph.res | 3 - .../valid/src/SelectionCoverage.res | 21 +- 18 files changed, 473 insertions(+), 258 deletions(-) create mode 100644 tests/authorization/invalid/src/UnsupportedInterface.res create mode 100644 tests/authorization/valid/src/AncestorGraph.res diff --git a/CHANGELOG.md b/CHANGELOG.md index ada49731..02aa6cb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,9 @@ ## Unreleased -- Allow field authorization policies to include their returned fields with - `{scope: Fields}`, including statically validated path coverage and - authorization-manifest provenance without repeated policy evaluation. +- Add explicit `@gql.authorize.byAncestor({reason})` dispositions with static + path-dominance validation, audit-manifest provenance, and no repeated runtime + policy evaluation. ## 1.3.0 diff --git a/docs/docs/authorization.md b/docs/docs/authorization.md index e0bdd25f..016e466b 100644 --- a/docs/docs/authorization.md +++ b/docs/docs/authorization.md @@ -88,17 +88,24 @@ Type, interface, field, and resolver policies compose additively. Interface fiel By default, a policy on a field returning an object does not authorize that object's child fields. Each output field needs its own disposition. -### Scoping authorization to returned fields +### Authorization by an ancestor -A field policy can explicitly include the fields returned beneath that field in -its authorization scope. This is useful for connection wrappers, mutation -payloads, and calculated result objects that have no authorization identity -independent of the field producing them: +Connection wrappers, mutation payloads, and calculated result objects often +have no authorization identity independent of the field that produced them. +After reviewing that relationship, mark their fields as authorized by an +ancestor: ```rescript -@gql.authorize( - (CampaignSecurity.canList, {scope: Fields}) -) +@gql.authorize.byAncestor({ + reason: "Connection fields expose only the authorized campaign result", +}) +@gql.type +type campaignConnection = { + @gql.field + edges: array, +} + +@gql.authorize(CampaignSecurity.canList) @gql.field let campaigns = async ( _: query, @@ -109,20 +116,27 @@ let campaigns = async ( } ``` -The inner parentheses form the ReScript tuple consumed by `@gql.authorize`. -ReScript infers the scope record from the regular `Fields` constructor, so -neither the record label nor constructor needs qualification. - -The policy runs once on `Query.campaigns`. Required authorization treats fields -reachable exclusively beneath that result as within its scope, without -generating additional policy calls for them. Local type and field policies still -run and compose additively when present. - -Field scope is path-sensitive. If the same result type is also reachable through -a path without a `scope: Fields` policy, its otherwise-uncovered fields fail -required authorization. Public fields and resolver outcomes do not widen a -policy's scope. `scope: Fields` is supported only on output fields and resolver -functions, not on type policies. +On a concrete object type, `@gql.authorize.byAncestor` is a default for each +immediate GraphQL field, including separately declared resolver fields. It is +not recursively copied to returned object types: `campaignEdge` must declare +its own disposition. The annotation can also be placed directly on one field. +A direct field policy, public declaration, or resolver outcome overrides a type +default. A field-level `byAncestor` annotation cannot be combined with one of +those direct dispositions. + +ResGraph statically proves that every root-to-field path crosses an ordinary +`@gql.authorize(...)` policy or an allowed resolver outcome before the annotated +field. A public field is not an authorization boundary. If the same object type +is reachable through an unprotected path, generation fails at the +`byAncestor` annotation. Lists and nullability are transparent to the proof; +unions and interface return types fan out to their concrete object types. +`byAncestor` is currently supported on concrete object types and fields, not on +interfaces or subscriptions. + +The annotation generates no runtime check. Upstream policies run only where +they are declared, so expensive authorization is not reevaluated for structural +child fields. Mutation root fields still require a pre-resolver policy; a +payload type may then use `byAncestor`. ## Resolver outcomes @@ -174,7 +188,7 @@ let onForbidden = ( ## Audit manifest and boundaries -`manifestPath` emits stable, sorted JSON with every concrete field, its disposition, policy order and provenance, inherited scope boundaries, public reason, source locations, resolver-outcome metadata, and mutation status. For a field reachable through multiple scoped paths, `scopeBoundaries` lists the possible boundary sources; only the boundary on the selected runtime path executes. Commit the manifest when authorization posture should be reviewed through diffs. +`manifestPath` emits stable, sorted JSON with every concrete field, its disposition, policy order and provenance, public or `byAncestor` review reason, source locations, resolver-outcome metadata, and mutation status. For an `authorizedByAncestor` field, `ancestorBoundaries` lists the nearest possible policy or resolver-outcome boundaries across its protected paths. Only policies declared on the selected runtime path execute. Commit the manifest when authorization posture should be reviewed through diffs. Fields on inferred union payload objects use the `synthetic` disposition. They have no annotation surface and are reachable only after their parent resolver diff --git a/src/ml/GenerateSchemaAuthorization.ml b/src/ml/GenerateSchemaAuthorization.ml index b388002c..aefea3ff 100644 --- a/src/ml/GenerateSchemaAuthorization.ml +++ b/src/ml/GenerateSchemaAuthorization.ml @@ -267,7 +267,7 @@ let validateFunction ~loader ~(package : SharedTypes.package) ~schemaState let declaration schemaState coordinate = match Hashtbl.find_opt schemaState.authorizationDeclarations coordinate with | Some declaration -> declaration - | None -> {functions = []; public = None} + | None -> {functions = []; public = None; byAncestor = None} type plannedReference = { reference: authorizationFunctionReference; @@ -319,6 +319,31 @@ let interfacePublic schemaState (typ : gqlObjectType) fieldName = ~parentTypeName:intf.displayName ~fieldName)) .public) +let addUnsupportedInterfaceAncestorDiagnostics (schemaState : schemaState) = + let check coordinate = + match (declaration schemaState coordinate).byAncestor with + | None -> () + | Some byAncestor -> + schemaState + |> addDiagnostic + ~diagnostic: + { + loc = byAncestor.loc; + fileUri = byAncestor.fileUri; + message = + "`@gql.authorize.byAncestor` is currently supported on \ + concrete object types and their fields, not interfaces."; + } + in + schemaState.interfaces + |> GenerateSchemaUtils.iterHashtblAlphabetically + (fun _ (intf : gqlInterface) -> + check intf.displayName; + intf.fields + |> List.iter (fun field -> + check + (GenerateSchemaUtils.authorizationCoordinate + ~parentTypeName:intf.displayName ~fieldName:field.name))) module BaselineEntry = struct type t = string * authorizationGapKind @@ -394,7 +419,7 @@ let loadBaseline path = BaselineEntries.empty let gapForField ~(typ : gqlObjectType) ~(field : gqlField) ~synthetic ~public - ~references ~inheritedScopePolicies ~resolverOutcome = + ~references ~byAncestor ~resolverOutcome = let coordinate = GenerateSchemaUtils.authorizationCoordinate ~parentTypeName:typ.displayName ~fieldName:field.name @@ -402,8 +427,7 @@ let gapForField ~(typ : gqlObjectType) ~(field : gqlField) ~synthetic ~public if typ.id = "subscription" then Some (coordinate, UnsupportedSubscription) else if synthetic then None else if - Option.is_none public && references = [] - && inheritedScopePolicies = [] + Option.is_none public && references = [] && Option.is_none byAncestor && Option.is_none resolverOutcome then Some (coordinate, UncoveredField) else if typ.id = "mutation" && Option.is_none public && references = [] then @@ -495,27 +519,58 @@ let buildFieldPlan ~loader ~package ~(schemaState : schemaState) coordinate; } | _ -> ()); + let hasDirectDisposition = + hasPolicies || Option.is_some public || Option.is_some resolverOutcome + in + let byAncestor = + match fieldDeclaration.byAncestor with + | Some byAncestor when hasDirectDisposition -> + let conflictAlreadyDiagnosed = + fieldDeclaration.functions <> [] + || Option.is_some fieldDeclaration.public + in + if not conflictAlreadyDiagnosed then + schemaState + |> addDiagnostic + ~diagnostic: + { + loc = byAncestor.loc; + fileUri = byAncestor.fileUri; + message = + Printf.sprintf + "`%s` is authorized by an ancestor but also has a direct \ + authorization disposition. Field-level direct policies, \ + public declarations, and resolver outcomes cannot be \ + combined with `@gql.authorize.byAncestor`." + coordinate; + }; + None + | Some byAncestor -> Some byAncestor + | None when hasDirectDisposition -> None + | None -> typeDeclaration.byAncestor + in Hashtbl.replace schemaState.authorizationPlans coordinate { functions; - inheritedScopePolicies = []; + byAncestor; + ancestorBoundaries = []; public; resolverOutcome; synthetic; baselineGap = None; } -module InheritedScopePolicy = struct - type t = inheritedScopePolicy +module AncestorAuthorizationBoundary = struct + type t = ancestorAuthorizationBoundary let compare = Stdlib.compare end -module InheritedScopePolicies = Set.Make (InheritedScopePolicy) +module AncestorAuthorizationBoundaries = Set.Make (AncestorAuthorizationBoundary) -type scopeReachability = { +type ancestorReachability = { hasUnprotectedPath: bool; - policies: InheritedScopePolicies.t; + boundaries: AncestorAuthorizationBoundaries.t; } let rec outputTypeIds ~processedSchema = function @@ -555,13 +610,18 @@ let fieldOutputTypeIds ~processedSchema (schemaState : schemaState) in ids field.typ |> List.sort_uniq String.compare -let scopePolicies coordinate (plan : effectiveAuthorizationPlan) = - plan.functions - |> List.filter_map (fun (fn : authorizationFunction) -> - match fn.reference.scope with - | AuthorizationField -> None - | AuthorizationFields -> Some {boundaryCoordinate = coordinate; fn}) - |> InheritedScopePolicies.of_list +let localAuthorizationBoundaries coordinate (plan : effectiveAuthorizationPlan) + = + let boundaries = + plan.functions + |> List.map (fun fn -> AncestorPolicy {boundaryCoordinate = coordinate; fn}) + in + match plan.resolverOutcome with + | None -> boundaries |> AncestorAuthorizationBoundaries.of_list + | Some outcome -> + AncestorResolverOutcome {boundaryCoordinate = coordinate; outcome} + :: boundaries + |> AncestorAuthorizationBoundaries.of_list let updateReachability reachability typeId incoming = match Hashtbl.find_opt reachability typeId with @@ -573,16 +633,21 @@ let updateReachability reachability typeId incoming = { hasUnprotectedPath = existing.hasUnprotectedPath || incoming.hasUnprotectedPath; - policies = - InheritedScopePolicies.union existing.policies incoming.policies; + boundaries = + AncestorAuthorizationBoundaries.union existing.boundaries + incoming.boundaries; } in - if merged = existing then false + if + Bool.equal merged.hasUnprotectedPath existing.hasUnprotectedPath + && AncestorAuthorizationBoundaries.equal merged.boundaries + existing.boundaries + then false else ( Hashtbl.replace reachability typeId merged; true) -let scopeReachability ~processedSchema (schemaState : schemaState) = +let ancestorReachability ~processedSchema (schemaState : schemaState) = let reachability = Hashtbl.create 50 in let pending = Queue.create () in let enqueueRoot = function @@ -590,7 +655,10 @@ let scopeReachability ~processedSchema (schemaState : schemaState) = | Some (typ : gqlObjectType) -> if updateReachability reachability typ.id - {hasUnprotectedPath = true; policies = InheritedScopePolicies.empty} + { + hasUnprotectedPath = true; + boundaries = AncestorAuthorizationBoundaries.empty; + } then Queue.add typ.id pending in enqueueRoot schemaState.query; @@ -610,14 +678,16 @@ let scopeReachability ~processedSchema (schemaState : schemaState) = ~parentTypeName:typ.displayName ~fieldName:field.name in let plan = Hashtbl.find schemaState.authorizationPlans coordinate in - let localPolicies = scopePolicies coordinate plan in + let localBoundaries = localAuthorizationBoundaries coordinate plan in let outgoing = { hasUnprotectedPath = incoming.hasUnprotectedPath - && InheritedScopePolicies.is_empty localPolicies; - policies = - InheritedScopePolicies.union incoming.policies localPolicies; + && AncestorAuthorizationBoundaries.is_empty localBoundaries; + boundaries = + (if AncestorAuthorizationBoundaries.is_empty localBoundaries + then incoming.boundaries + else localBoundaries); } in fieldOutputTypeIds ~processedSchema schemaState field @@ -628,17 +698,10 @@ let scopeReachability ~processedSchema (schemaState : schemaState) = done; reachability -let applyInheritedScopePolicies ~processedSchema (schemaState : schemaState) = - let reachability = scopeReachability ~processedSchema schemaState in +let applyAncestorAuthorization ~processedSchema (schemaState : schemaState) = + let reachability = ancestorReachability ~processedSchema schemaState in schemaState.types |> Hashtbl.iter (fun typeId (typ : gqlObjectType) -> - let inheritedScopePolicies = - match Hashtbl.find_opt reachability typeId with - | Some {hasUnprotectedPath = false; policies} - when not (InheritedScopePolicies.is_empty policies) -> - InheritedScopePolicies.elements policies - | _ -> [] - in typ.fields |> List.iter (fun field -> let coordinate = @@ -647,9 +710,32 @@ let applyInheritedScopePolicies ~processedSchema (schemaState : schemaState) = in match Hashtbl.find_opt schemaState.authorizationPlans coordinate with | None -> () - | Some plan -> - Hashtbl.replace schemaState.authorizationPlans coordinate - {plan with inheritedScopePolicies})) + | Some {byAncestor = None} -> () + | Some ({byAncestor = Some byAncestor} as plan) -> ( + match Hashtbl.find_opt reachability typeId with + | Some {hasUnprotectedPath = false; boundaries} + when not (AncestorAuthorizationBoundaries.is_empty boundaries) -> + Hashtbl.replace schemaState.authorizationPlans coordinate + { + plan with + ancestorBoundaries = + AncestorAuthorizationBoundaries.elements boundaries; + } + | _ -> + schemaState + |> addDiagnostic + ~diagnostic: + { + loc = byAncestor.loc; + fileUri = byAncestor.fileUri; + message = + Printf.sprintf + "Field `%s` uses `@gql.authorize.byAncestor`, but \ + ResGraph cannot prove that every path to it \ + crosses a preceding authorization policy or \ + resolver outcome." + coordinate; + }))) let finalizeFieldPlan ~(schemaState : schemaState) ~baselineEntries ~skipGapDiagnostics ~(typ : gqlObjectType) ~(field : gqlField) = @@ -664,7 +750,7 @@ let finalizeFieldPlan ~(schemaState : schemaState) ~baselineEntries in let gap = gapForField ~typ ~field ~synthetic:plan.synthetic ~public:plan.public - ~references ~inheritedScopePolicies:plan.inheritedScopePolicies + ~references ~byAncestor:plan.byAncestor ~resolverOutcome:plan.resolverOutcome in let baselineGap = @@ -723,13 +809,14 @@ let buildPlans ~loader ~package ~processedSchema (schemaState : schemaState) = (None, true)) | _ -> (None, false) in + addUnsupportedInterfaceAncestorDiagnostics schemaState; schemaState.types |> GenerateSchemaUtils.iterHashtblAlphabetically (fun _ (typ : gqlObjectType) -> typ.fields |> List.iter (fun field -> buildFieldPlan ~loader ~package ~schemaState ~typ ~field)); - applyInheritedScopePolicies ~processedSchema schemaState; + applyAncestorAuthorization ~processedSchema schemaState; schemaState.types |> GenerateSchemaUtils.iterHashtblAlphabetically (fun _ (typ : gqlObjectType) -> @@ -759,24 +846,24 @@ let provenanceToString = function | FieldPolicy coordinate -> "field:" ^ coordinate let manifestPolicy ~package (fn : authorizationFunction) = - let scope = - match fn.reference.scope with - | AuthorizationField -> "" - | AuthorizationFields -> ",\"scope\":\"fields\"" - in Printf.sprintf - "{\"path\":%s,\"provenance\":%s,\"file\":%s,\"location\":%s,\"async\":%s%s}" + "{\"path\":%s,\"provenance\":%s,\"file\":%s,\"location\":%s,\"async\":%s}" (jsonString (GenerateSchemaUtils.authorizationFunctionName fn.reference)) (jsonString (provenanceToString fn.provenance)) (jsonString (relativeSourcePath ~package fn.reference.fileUri)) (jsonString (Loc.toString fn.reference.loc)) (if fn.isAsync then "true" else "false") - scope -let manifestScopeBoundary ~package (policy : inheritedScopePolicy) = - Printf.sprintf "{\"boundary\":%s,\"policy\":%s}" - (jsonString policy.boundaryCoordinate) - (manifestPolicy ~package policy.fn) +let manifestAncestorBoundary ~package = function + | AncestorPolicy {boundaryCoordinate; fn} -> + Printf.sprintf "{\"coordinate\":%s,\"kind\":\"policy\",\"policy\":%s}" + (jsonString boundaryCoordinate) + (manifestPolicy ~package fn) + | AncestorResolverOutcome {boundaryCoordinate; outcome = {isAsync}} -> + Printf.sprintf + "{\"coordinate\":%s,\"kind\":\"resolverOutcome\",\"resolverOutcome\":{\"async\":%s}}" + (jsonString boundaryCoordinate) + (if isAsync then "true" else "false") let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = let disposition = @@ -785,7 +872,7 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = plan.synthetic, plan.public, plan.functions, - plan.inheritedScopePolicies, + plan.byAncestor, plan.resolverOutcome ) with | Some _, _, _, _, _, _ -> "baseline" @@ -793,8 +880,8 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = | None, false, Some _, _, _, _ -> "public" | None, false, None, _ :: _, _, _ -> "policies" | None, false, None, [], _, Some _ -> "resolverOutcome" - | None, false, None, [], _ :: _, None -> "scope" - | None, false, None, [], [], None -> "uncovered" + | None, false, None, [], Some _, None -> "authorizedByAncestor" + | None, false, None, [], None, None -> "uncovered" in let publicJson = match plan.public with @@ -805,28 +892,37 @@ let manifestField ~package coordinate (plan : effectiveAuthorizationPlan) = (jsonString (relativeSourcePath ~package public.fileUri)) (jsonString (Loc.toString public.loc)) in + let byAncestorJson = + match plan.byAncestor with + | None -> "null" + | Some byAncestor -> + Printf.sprintf "{\"reason\":%s,\"file\":%s,\"location\":%s}" + (jsonString byAncestor.reason) + (jsonString (relativeSourcePath ~package byAncestor.fileUri)) + (jsonString (Loc.toString byAncestor.loc)) + in let resolverOutcomeJson = match plan.resolverOutcome with | None -> "null" | Some {isAsync} -> Printf.sprintf "{\"async\":%s}" (if isAsync then "true" else "false") in - let inheritedScopeJson = - match plan.inheritedScopePolicies with + let ancestorBoundariesJson = + match plan.ancestorBoundaries with | [] -> "" - | policies -> - Printf.sprintf ",\"scopeBoundaries\":[%s]" - (policies - |> List.map (manifestScopeBoundary ~package) + | boundaries -> + Printf.sprintf ",\"ancestorBoundaries\":[%s]" + (boundaries + |> List.map (manifestAncestorBoundary ~package) |> String.concat ",") in Printf.sprintf - "{\"coordinate\":%s,\"disposition\":%s,\"mutation\":%s,\"policies\":[%s],\"public\":%s,\"resolverOutcome\":%s%s}" + "{\"coordinate\":%s,\"disposition\":%s,\"mutation\":%s,\"policies\":[%s],\"public\":%s,\"byAncestor\":%s,\"resolverOutcome\":%s%s}" (jsonString coordinate) (jsonString disposition) (if String.starts_with coordinate ~prefix:"Mutation." then "true" else "false") (plan.functions |> List.map (manifestPolicy ~package) |> String.concat ",") - publicJson resolverOutcomeJson inheritedScopeJson + publicJson byAncestorJson resolverOutcomeJson ancestorBoundariesJson let rec ensureDirectory path = if path = "" || path = "." || Sys.file_exists path then () diff --git a/src/ml/GenerateSchemaTypePrinters.ml b/src/ml/GenerateSchemaTypePrinters.ml index 6d4a3b8b..19b3ed39 100644 --- a/src/ml/GenerateSchemaTypePrinters.ml +++ b/src/ml/GenerateSchemaTypePrinters.ml @@ -47,7 +47,8 @@ let printResolverForField ~parentTypeName ~(schemaState : schemaState) | None -> { functions = []; - inheritedScopePolicies = []; + byAncestor = None; + ancestorBoundaries = []; public = None; resolverOutcome = Hashtbl.find_opt schemaState.resolverOutcomes coordinate; diff --git a/src/ml/GenerateSchemaTypes.ml b/src/ml/GenerateSchemaTypes.ml index c68d954b..afbe0572 100644 --- a/src/ml/GenerateSchemaTypes.ml +++ b/src/ml/GenerateSchemaTypes.ml @@ -39,20 +39,20 @@ type authorizationConfig = { baselinePath: string option; } -type authorizationScope = AuthorizationField | AuthorizationFields - type authorizationFunctionReference = { path: string list; loc: Location.t; fileUri: Uri.t; - scope: authorizationScope; } type publicAuthorization = {reason: string; loc: Location.t; fileUri: Uri.t} +type ancestorAuthorization = {reason: string; loc: Location.t; fileUri: Uri.t} + type declaredAuthorization = { functions: authorizationFunctionReference list; public: publicAuthorization option; + byAncestor: ancestorAuthorization option; } type authorizationInjection = AuthorizationContext | AuthorizationInfo @@ -79,17 +79,20 @@ type authorizationGapKind = type effectiveAuthorizationPlan = { functions: authorizationFunction list; - inheritedScopePolicies: inheritedScopePolicy list; + byAncestor: ancestorAuthorization option; + ancestorBoundaries: ancestorAuthorizationBoundary list; public: publicAuthorization option; resolverOutcome: resolverOutcome option; synthetic: bool; baselineGap: authorizationGapKind option; } -and inheritedScopePolicy = { - boundaryCoordinate: string; - fn: authorizationFunction; -} +and ancestorAuthorizationBoundary = + | AncestorPolicy of {boundaryCoordinate: string; fn: authorizationFunction} + | AncestorResolverOutcome of { + boundaryCoordinate: string; + outcome: resolverOutcome; + } type typeLocationLoc = { fileName: string; diff --git a/src/ml/GenerateSchemaUtils.ml b/src/ml/GenerateSchemaUtils.ml index 51382173..79693cee 100644 --- a/src/ml/GenerateSchemaUtils.ml +++ b/src/ml/GenerateSchemaUtils.ml @@ -43,6 +43,8 @@ let validAttributes = ("gql.scalar", ""); ("gql.authorize", "Attaches a typed authorization function."); ("gql.public", "Marks a field public with a required reason."); + ( "gql.authorize.byAncestor", + "Marks a field as authorized by a policy on every path to it." ); ] let hasGqlAnnotation attributes = @@ -93,7 +95,10 @@ let extractGqlAttribute ~(schemaState : GenerateSchemaTypes.schemaState) | ["gql"; "union"] -> Some Union | ["gql"; "inputObject"] -> Some InputObject | ["gql"; "inputUnion"] -> Some InputUnion - | ["gql"; "authorize"] | ["gql"; "public"] -> None + | ["gql"; "authorize"] + | ["gql"; "authorize"; "byAncestor"] + | ["gql"; "public"] -> + None | "gql" :: _ -> schemaState |> addDiagnostic @@ -148,7 +153,7 @@ let extractGqlImplementsAttributes | _ -> None) let emptyDeclaredAuthorization : declaredAuthorization = - {functions = []; public = None} + {functions = []; public = None; byAncestor = None} let authorizationCoordinate ~parentTypeName ~fieldName = parentTypeName ^ "." ^ fieldName @@ -162,50 +167,16 @@ let addAuthorizationDiagnostic ~schemaState ~(env : SharedTypes.QueryEnv.t) ~loc |> addDiagnostic ~diagnostic:{loc; fileUri = env.SharedTypes.QueryEnv.file.uri; message} -let authorizationScopeFromRecord ~schemaState ~(env : SharedTypes.QueryEnv.t) - ~attributeLoc fields = - let scopeFields = - fields - |> List.filter - (fun (field : Parsetree.expression Parsetree.record_element) -> - Longident.last field.lid.txt = "scope") - in - match (fields, scopeFields) with - | [_], [field] -> ( - match field.x.pexp_desc with - | Pexp_construct ({txt = constructor}, None) - when Longident.last constructor = "Fields" -> - Some AuthorizationFields - | _ -> - addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.authorize` scope must be the `Fields` constructor, for example \ - `@gql.authorize((Security.canRead, {scope: Fields}))`."; - None) - | [], _ | _, [] -> - addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.authorize` scope requires `{scope: Fields}` in its tuple payload."; - None - | _ -> - addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.authorize` scope accepts only `{scope: Fields}`."; - None - -let functionReferenceFromPayload ~allowFieldsScope ~schemaState - ~(env : SharedTypes.QueryEnv.t) ~attributeLoc (payload : Parsetree.payload) - = - let reference functionPath scope = +let functionReferenceFromPayload ~schemaState ~(env : SharedTypes.QueryEnv.t) + ~attributeLoc (payload : Parsetree.payload) = + let reference functionPath = let path = Longident.flatten functionPath in if List.length path < 2 then ( addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc "`@gql.authorize` requires a module-qualified function path, for \ example `Security.canRead`."; None) - else if scope = AuthorizationFields && not allowFieldsScope then ( - addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.authorize((..., {scope: Fields}))` can only be used on output \ - fields or resolver functions, not on a type."; - None) - else Some {path; loc = attributeLoc; fileUri = env.file.uri; scope} + else Some {path; loc = attributeLoc; fileUri = env.file.uri} in match payload with | PStr @@ -215,36 +186,16 @@ let functionReferenceFromPayload ~allowFieldsScope ~schemaState Pstr_eval ({pexp_desc = Pexp_ident {txt = functionPath}}, _); }; ] -> - reference functionPath AuthorizationField - | PStr - [ - { - pstr_desc = - Pstr_eval - ( { - pexp_desc = - Pexp_tuple - [ - {pexp_desc = Pexp_ident {txt = functionPath}}; - {pexp_desc = Pexp_record (fields, None)}; - ]; - }, - _ ); - }; - ] -> ( - match - authorizationScopeFromRecord ~schemaState ~env ~attributeLoc fields - with - | None -> None - | Some scope -> reference functionPath scope) + reference functionPath | _ -> addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc "`@gql.authorize` requires a module-qualified function path, for example \ `Security.canRead`."; None -let publicReasonFromPayload ~schemaState ~(env : SharedTypes.QueryEnv.t) - ~attributeLoc (payload : Parsetree.payload) = +let reasonStringFromPayload ~annotation ~schemaState + ~(env : SharedTypes.QueryEnv.t) ~attributeLoc (payload : Parsetree.payload) + = let reason = match payload with | PStr @@ -269,54 +220,91 @@ let publicReasonFromPayload ~schemaState ~(env : SharedTypes.QueryEnv.t) 0 in match reason with - | Some reason when nonWhitespaceLength reason >= 3 -> - Some {reason; loc = attributeLoc; fileUri = env.file.uri} + | Some reason when nonWhitespaceLength reason >= 3 -> Some reason | _ -> addAuthorizationDiagnostic ~schemaState ~env ~loc:attributeLoc - "`@gql.public` requires a reason with at least 3 non-whitespace \ - characters, for example `@gql.public({reason: \"Public profile \ - data\"})`."; + (Printf.sprintf + "`%s` requires a reason with at least 3 non-whitespace characters, \ + for example `%s({reason: \"Reviewed authorization disposition\"})`." + annotation annotation); None let extractDeclaredAuthorization ~allowPublic ~schemaState ~(env : SharedTypes.QueryEnv.t) (attributes : Parsetree.attributes) = - attributes - |> List.fold_left - (fun (declared : declaredAuthorization) - ((name, payload) : Parsetree.attribute) -> - match String.split_on_char '.' name.txt with - | ["gql"; "authorize"] -> ( - match - functionReferenceFromPayload ~allowFieldsScope:allowPublic - ~schemaState ~env ~attributeLoc:name.loc payload - with - | None -> declared - | Some fn -> {declared with functions = declared.functions @ [fn]}) - | ["gql"; "public"] -> ( - if not allowPublic then ( - addAuthorizationDiagnostic ~schemaState ~env ~loc:name.loc - "`@gql.public` can only be used on output fields or resolver \ - functions, not on a type."; - declared) - else + let declared = + attributes + |> List.fold_left + (fun (declared : declaredAuthorization) + ((name, payload) : Parsetree.attribute) -> + match String.split_on_char '.' name.txt with + | ["gql"; "authorize"] -> ( match - publicReasonFromPayload ~schemaState ~env ~attributeLoc:name.loc - payload + functionReferenceFromPayload ~schemaState ~env + ~attributeLoc:name.loc payload with | None -> declared - | Some public -> ( - match declared.public with - | None -> {declared with public = Some public} + | Some fn -> {declared with functions = declared.functions @ [fn]}) + | ["gql"; "authorize"; "byAncestor"] -> ( + match + reasonStringFromPayload ~annotation:"@gql.authorize.byAncestor" + ~schemaState ~env ~attributeLoc:name.loc payload + with + | None -> declared + | Some reason -> ( + match declared.byAncestor with + | None -> + { + declared with + byAncestor = + Some {reason; loc = name.loc; fileUri = env.file.uri}; + } | Some _ -> addAuthorizationDiagnostic ~schemaState ~env ~loc:name.loc - "Only one `@gql.public` annotation is allowed per field."; + "Only one `@gql.authorize.byAncestor` annotation is allowed \ + per field or type."; declared)) - | _ -> declared) - emptyDeclaredAuthorization + | ["gql"; "public"] -> ( + if not allowPublic then ( + addAuthorizationDiagnostic ~schemaState ~env ~loc:name.loc + "`@gql.public` can only be used on output fields or resolver \ + functions, not on a type."; + declared) + else + match + reasonStringFromPayload ~annotation:"@gql.public" ~schemaState + ~env ~attributeLoc:name.loc payload + with + | None -> declared + | Some reason -> ( + match declared.public with + | None -> + { + declared with + public = + Some {reason; loc = name.loc; fileUri = env.file.uri}; + } + | Some _ -> + addAuthorizationDiagnostic ~schemaState ~env ~loc:name.loc + "Only one `@gql.public` annotation is allowed per field."; + declared)) + | _ -> declared) + emptyDeclaredAuthorization + in + (match (declared.byAncestor, declared.functions, declared.public) with + | Some byAncestor, _ :: _, _ | Some byAncestor, _, Some _ -> + addAuthorizationDiagnostic ~schemaState ~env ~loc:byAncestor.loc + "`@gql.authorize.byAncestor` cannot be combined with \ + `@gql.authorize(...)` or `@gql.public` on the same field or type." + | _ -> ()); + declared let registerAuthorizationDeclaration ~coordinate (declared : declaredAuthorization) ~(schemaState : schemaState) = - if declared.functions = [] && Option.is_none declared.public then () + if + declared.functions = [] + && Option.is_none declared.public + && Option.is_none declared.byAncestor + then () else match Hashtbl.find_opt schemaState.authorizationDeclarations coordinate with | None -> @@ -333,6 +321,10 @@ let registerAuthorizationDeclaration ~coordinate (match (existing.public, declared.public) with | Some public, _ -> Some public | None, public -> public); + byAncestor = + (match (existing.byAncestor, declared.byAncestor) with + | Some byAncestor, _ -> Some byAncestor + | None, byAncestor -> byAncestor); } let registerAuthorizationAttributes ~coordinate ~allowPublic ~attributes diff --git a/src/res/ResGraph.res b/src/res/ResGraph.res index 18cd348f..d5a0165e 100644 --- a/src/res/ResGraph.res +++ b/src/res/ResGraph.res @@ -16,9 +16,6 @@ module Connections = ResGraph__Connections module Utils = ResGraph__Utils module Authorization = { - type scope = Fields - type scopeOptions = {scope: scope} - type outcome<'value, 'reason> = | Allowed('value) | Forbidden('reason) diff --git a/tests/authorization/baseline/src/ResGraph.res b/tests/authorization/baseline/src/ResGraph.res index 18f4644f..72b9c403 100644 --- a/tests/authorization/baseline/src/ResGraph.res +++ b/tests/authorization/baseline/src/ResGraph.res @@ -1,9 +1,6 @@ type resolveInfo = unit module Authorization = { - type scope = Fields - type scopeOptions = {scope: scope} - type outcome<'value, 'reason> = | Allowed('value) | Forbidden('reason) diff --git a/tests/authorization/invalid/src/Query.res b/tests/authorization/invalid/src/Query.res index b89fa3bd..da2735d5 100644 --- a/tests/authorization/invalid/src/Query.res +++ b/tests/authorization/invalid/src/Query.res @@ -1,6 +1,4 @@ -@gql.public({reason: "Types cannot be public"}) -@gql.authorize((Security.good, {scope: Fields})) -@gql.type +@gql.public({reason: "Types cannot be public"}) @gql.type type query @gql.field @@ -43,16 +41,30 @@ let badContext = (_: query): string => "bad context" let nonUnitOutcome = (_: query): string => "bad outcome" @gql.type +@gql.authorize.byAncestor({reason: "Shared selection fields rely on their protected entry path"}) type sharedSelection = { @gql.field value: string, } -@gql.authorize( - (Security.canSelect, {scope: Fields}) -) -@gql.field +@gql.authorize(Security.canSelect) @gql.field let protectedSelection = (_: query): sharedSelection => {value: "protected"} @gql.public({reason: "Intentionally exercises an unprotected alternate path"}) @gql.field let publicSelection = (_: query): sharedSelection => {value: "public"} + +@gql.authorize.byAncestor({reason: "Root field incorrectly claims an ancestor policy"}) @gql.field +let noAncestor = (_: query): string => "no ancestor" + +@gql.authorize.byAncestor({reason: "Conflicts with a direct field policy"}) +@gql.authorize(Security.good) +@gql.field +let ancestorConflict = (_: query): string => "conflict" + +@gql.authorize.byAncestor({reason: "a b"}) @gql.field +let shortAncestorReason = (_: query): string => "short" + +@gql.authorize.byAncestor({reason: "First review"}) +@gql.authorize.byAncestor({reason: "Second review"}) +@gql.field +let duplicateAncestor = (_: query): string => "duplicate" diff --git a/tests/authorization/invalid/src/ResGraph.res b/tests/authorization/invalid/src/ResGraph.res index b8b45314..97ecee76 100644 --- a/tests/authorization/invalid/src/ResGraph.res +++ b/tests/authorization/invalid/src/ResGraph.res @@ -1,7 +1,4 @@ type resolveInfo = unit module Authorization = { - type scope = Fields - type scopeOptions = {scope: scope} - type outcome<'value, 'reason> = Allowed('value) | Forbidden('reason) } diff --git a/tests/authorization/invalid/src/UnsupportedInterface.res b/tests/authorization/invalid/src/UnsupportedInterface.res new file mode 100644 index 00000000..5be72cf9 --- /dev/null +++ b/tests/authorization/invalid/src/UnsupportedInterface.res @@ -0,0 +1,11 @@ +@gql.authorize.byAncestor({reason: "Interface fields rely on an upstream policy"}) @gql.interface +type unsupportedAncestor = { + @gql.authorize.byAncestor({reason: "Interface field relies on an upstream policy"}) @gql.field + value: string, +} + +@gql.implements("UnsupportedAncestor") @gql.type +type unsupportedConcrete = { + @gql.field + value: string, +} diff --git a/tests/authorization/run-tests.sh b/tests/authorization/run-tests.sh index 67674d6f..fa98f702 100755 --- a/tests/authorization/run-tests.sh +++ b/tests/authorization/run-tests.sh @@ -59,11 +59,28 @@ grep -F 'switch Security.canReadNamed(Obj.magic(src)' "$tmp_dir/valid/ResGraphSc grep -F 'switch Security.first' "$tmp_dir/valid/ResGraphSchema.res" >/dev/null grep -F 'switch Security.Alias.second' "$tmp_dir/valid/ResGraphSchema.res" >/dev/null if [[ "$(grep -c 'switch Security.canLoadSelection' "$tmp_dir/valid/ResGraphSchema.res")" -ne 1 ]]; then - echo "Fields-scoped policy was not emitted exactly once at its boundary." >&2 + echo "Ancestor policy was not emitted exactly once at its declared field." >&2 exit 1 fi diff -u "$root_dir/tests/authorization/valid/expected-authorization-manifest.json" \ "$tmp_dir/valid/authorization-manifest.json" +jq -e ' + . as $manifest | + ([$manifest.fields[] | select(.disposition == "authorizedByAncestor")] | length) == 9 and + ($manifest.fields[] | select(.coordinate == "OutcomePayload.value") | + .ancestorBoundaries == [{ + "coordinate": "Query.outcomePayload", + "kind": "resolverOutcome", + "resolverOutcome": {"async": false} + }]) and + ($manifest.fields[] | select(.coordinate == "SelectionConnection.label") | + .disposition == "public" and .byAncestor == null) and + ($manifest.fields[] | select(.coordinate == "SharedProtected.value") | + [.ancestorBoundaries[].coordinate] == [ + "Query.firstShared", + "Query.secondShared" + ])' \ + "$tmp_dir/valid/authorization-manifest.json" >/dev/null mkdir -p "$tmp_dir/manifest-upgrade" cp "$root_dir/tests/authorization/valid/expected-authorization-manifest.json" \ @@ -123,9 +140,17 @@ grep -F 'has source type `Mutation`, but it is applied to `Query`' \ grep -F 'must declare `~args` as a ReScript polymorphic object' \ "$tmp_dir/invalid-result.json" >/dev/null grep -F 'has invalid `~ctx`' "$tmp_dir/invalid-result.json" >/dev/null -grep -F '`@gql.authorize((..., {scope: Fields}))` can only be used on output fields' \ +grep -F '`@gql.authorize.byAncestor` cannot be combined with `@gql.authorize(...)`' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Only one `@gql.authorize.byAncestor` annotation is allowed' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F '`@gql.authorize.byAncestor` requires a reason with at least 3' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Field `Query.noAncestor` uses `@gql.authorize.byAncestor`' \ + "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Field `SharedSelection.value` uses `@gql.authorize.byAncestor`' \ "$tmp_dir/invalid-result.json" >/dev/null -grep -F 'Field `SharedSelection.value` has no authorization disposition.' \ +grep -F '`@gql.authorize.byAncestor` is currently supported on concrete object types' \ "$tmp_dir/invalid-result.json" >/dev/null grep -F 'Required authorization coverage does not support subscription field `Subscription.events` yet.' \ "$tmp_dir/invalid-result.json" >/dev/null diff --git a/tests/authorization/valid/expected-authorization-manifest.json b/tests/authorization/valid/expected-authorization-manifest.json index 1591d51f..164061c9 100644 --- a/tests/authorization/valid/expected-authorization-manifest.json +++ b/tests/authorization/valid/expected-authorization-manifest.json @@ -3,40 +3,51 @@ "version": 2, "status": "success", "fields": [ - {"coordinate":"DeclaredResultFailure.message","disposition":"synthetic","mutation":false,"policies":[],"public":null,"resolverOutcome":null}, - {"coordinate":"DeclaredResultSuccess.value","disposition":"synthetic","mutation":false,"policies":[],"public":null,"resolverOutcome":null}, - {"coordinate":"Device.name","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadNamed","provenance":"interfaceType:Named","file":"src/Named.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Device.serial","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadNamed","provenance":"interfaceType:Named","file":"src/Named.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"InferredFailure.message","disposition":"synthetic","mutation":false,"policies":[],"public":null,"resolverOutcome":null}, - {"coordinate":"InferredSuccess.value","disposition":"synthetic","mutation":false,"policies":[],"public":null,"resolverOutcome":null}, - {"coordinate":"InheritedOutcomeDevice.computed","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":false}}, - {"coordinate":"InheritedOutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public across this interface","file":"src/OutcomeNamed.res","location":"[2:2->2:13]"},"resolverOutcome":null}, - {"coordinate":"MultiOutcomeDevice.computed","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Plain computed values are public","file":"src/PlainNamed.res","location":"[6:0->6:11]"},"resolverOutcome":null}, - {"coordinate":"MultiOutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public on the plain interface","file":"src/PlainNamed.res","location":"[2:2->2:13]"},"resolverOutcome":null}, - {"coordinate":"Mutation.ping","disposition":"public","mutation":true,"policies":[],"public":{"reason":"Explicitly public mutation used by uptime checks","file":"src/Mutation.res","location":"[6:0->6:11]"},"resolverOutcome":null}, - {"coordinate":"Mutation.update","disposition":"policies","mutation":true,"policies":[{"path":"Security.canMutate","provenance":"field:Mutation.update","file":"src/Mutation.res","location":"[3:0->3:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"OutcomeDevice.computed","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Concrete override has its own public disposition","file":"src/OutcomeDevice.res","location":"[12:0->12:11]"},"resolverOutcome":null}, - {"coordinate":"OutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public across this interface","file":"src/OutcomeNamed.res","location":"[2:2->2:13]"},"resolverOutcome":null}, - {"coordinate":"PublicDevice.label","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Names are public across this interface","file":"src/PublicNamed.res","location":"[2:2->2:13]"},"resolverOutcome":null}, - {"coordinate":"Query.aliasedAsyncOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":true}}, - {"coordinate":"Query.aliasedOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":false}}, - {"coordinate":"Query.asyncOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":true}}, - {"coordinate":"Query.asyncValue","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadAsync","provenance":"field:Query.asyncValue","file":"src/Query.res","location":"[17:0->17:14]","async":true}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.declared","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.declared","file":"src/Query.res","location":"[44:0->44:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.device","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadDevice","provenance":"field:Query.device","file":"src/Query.res","location":"[20:0->20:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.health","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Health check contains no private data","file":"src/Query.res","location":"[5:0->5:11]"},"resolverOutcome":null}, - {"coordinate":"Query.inferred","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.inferred","file":"src/Query.res","location":"[26:0->26:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.ordered","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.ordered","file":"src/Query.res","location":"[23:0->23:14]","async":false},{"path":"Security.Alias.second","provenance":"field:Query.ordered","file":"src/Query.res","location":"[23:31->23:45]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.outcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"resolverOutcome":{"async":false}}, - {"coordinate":"Query.outcomeDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadOutcomeDevice","provenance":"field:Query.outcomeDevice","file":"src/Query.res","location":"[38:0->38:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.publicDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadPublicDevice","provenance":"field:Query.publicDevice","file":"src/Query.res","location":"[35:0->35:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.selection","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"scope":"fields"}],"public":null,"resolverOutcome":null}, - {"coordinate":"Query.user","disposition":"policies","mutation":false,"policies":[{"path":"Security.canFindUser","provenance":"field:Query.user","file":"src/Query.res","location":"[8:0->8:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"SelectionConnection.edges","disposition":"scope","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"scopeBoundaries":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"scope":"fields"}}]}, - {"coordinate":"SelectionEdge.cursor","disposition":"scope","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"scopeBoundaries":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"scope":"fields"}}]}, - {"coordinate":"SelectionEdge.node","disposition":"scope","mutation":false,"policies":[],"public":null,"resolverOutcome":null,"scopeBoundaries":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"scope":"fields"}}]}, - {"coordinate":"SelectionNode.value","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadSelectionNode","provenance":"objectType:SelectionNode","file":"src/SelectionCoverage.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null,"scopeBoundaries":[{"boundary":"Query.selection","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false,"scope":"fields"}}]}, - {"coordinate":"User.id","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false}],"public":null,"resolverOutcome":null}, - {"coordinate":"User.secret","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:2->4:16]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:39->4:53]","async":false}],"public":null,"resolverOutcome":null} + {"coordinate":"AncestorAlpha.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Union member fields are governed by the query policy","file":"src/AncestorGraph.res","location":"[0:0->0:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.ancestorUnion","kind":"policy","policy":{"path":"Security.first","provenance":"field:Query.ancestorUnion","file":"src/AncestorGraph.res","location":"[17:0->17:14]","async":false}}]}, + {"coordinate":"AncestorBeta.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Union member fields are governed by the query policy","file":"src/AncestorGraph.res","location":"[7:0->7:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.ancestorUnion","kind":"policy","policy":{"path":"Security.first","provenance":"field:Query.ancestorUnion","file":"src/AncestorGraph.res","location":"[17:0->17:14]","async":false}}]}, + {"coordinate":"DeclaredResultFailure.message","disposition":"synthetic","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"DeclaredResultSuccess.value","disposition":"synthetic","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Device.name","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadNamed","provenance":"interfaceType:Named","file":"src/Named.res","location":"[0:0->0:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Device.serial","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadNamed","provenance":"interfaceType:Named","file":"src/Named.res","location":"[0:0->0:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"InferredFailure.message","disposition":"synthetic","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"InferredSuccess.value","disposition":"synthetic","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"InheritedOutcomeDevice.computed","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":false}}, + {"coordinate":"InheritedOutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public across this interface","file":"src/OutcomeNamed.res","location":"[2:2->2:13]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"MultiOutcomeDevice.computed","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Plain computed values are public","file":"src/PlainNamed.res","location":"[6:0->6:11]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"MultiOutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public on the plain interface","file":"src/PlainNamed.res","location":"[2:2->2:13]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Mutation.ping","disposition":"public","mutation":true,"policies":[],"public":{"reason":"Explicitly public mutation used by uptime checks","file":"src/Mutation.res","location":"[13:0->13:11]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Mutation.update","disposition":"policies","mutation":true,"policies":[{"path":"Security.canMutate","provenance":"field:Mutation.update","file":"src/Mutation.res","location":"[10:0->10:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"OutcomeDevice.computed","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Concrete override has its own public disposition","file":"src/OutcomeDevice.res","location":"[12:0->12:11]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"OutcomeDevice.id","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Identifiers are public across this interface","file":"src/OutcomeNamed.res","location":"[2:2->2:13]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"OutcomePayload.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Payload is exposed only after its resolver outcome allows access","file":"src/SelectionCoverage.res","location":"[31:0->31:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.outcomePayload","kind":"resolverOutcome","resolverOutcome":{"async":false}}]}, + {"coordinate":"PublicDevice.label","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Names are public across this interface","file":"src/PublicNamed.res","location":"[2:2->2:13]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.aliasedAsyncOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":true}}, + {"coordinate":"Query.aliasedOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":false}}, + {"coordinate":"Query.ancestorUnion","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.ancestorUnion","file":"src/AncestorGraph.res","location":"[17:0->17:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.asyncOutcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":true}}, + {"coordinate":"Query.asyncValue","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadAsync","provenance":"field:Query.asyncValue","file":"src/Query.res","location":"[17:0->17:14]","async":true}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.declared","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.declared","file":"src/Query.res","location":"[44:0->44:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.device","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadDevice","provenance":"field:Query.device","file":"src/Query.res","location":"[20:0->20:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.firstShared","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.firstShared","file":"src/AncestorGraph.res","location":"[27:0->27:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.health","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Health check contains no private data","file":"src/Query.res","location":"[5:0->5:11]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.inferred","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.inferred","file":"src/Query.res","location":"[26:0->26:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.ordered","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.ordered","file":"src/Query.res","location":"[23:0->23:14]","async":false},{"path":"Security.Alias.second","provenance":"field:Query.ordered","file":"src/Query.res","location":"[23:31->23:45]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.outcome","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":false}}, + {"coordinate":"Query.outcomeDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadOutcomeDevice","provenance":"field:Query.outcomeDevice","file":"src/Query.res","location":"[38:0->38:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.outcomePayload","disposition":"resolverOutcome","mutation":false,"policies":[],"public":null,"byAncestor":null,"resolverOutcome":{"async":false}}, + {"coordinate":"Query.publicDevice","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadPublicDevice","provenance":"field:Query.publicDevice","file":"src/Query.res","location":"[35:0->35:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.secondShared","disposition":"policies","mutation":false,"policies":[{"path":"Security.first","provenance":"field:Query.secondShared","file":"src/AncestorGraph.res","location":"[30:0->30:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.selection","disposition":"policies","mutation":false,"policies":[{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"Query.user","disposition":"policies","mutation":false,"policies":[{"path":"Security.canFindUser","provenance":"field:Query.user","file":"src/Query.res","location":"[8:0->8:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"SelectionConnection.edges","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Structural connection fields are governed by the selection query","file":"src/SelectionCoverage.res","location":"[20:0->20:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.selection","kind":"policy","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false}}]}, + {"coordinate":"SelectionConnection.label","disposition":"public","mutation":false,"policies":[],"public":{"reason":"Static label contains no protected data","file":"src/SelectionCoverage.res","location":"[27:2->27:13]"},"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"SelectionEdge.cursor","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Structural edge fields are governed by the selection query","file":"src/SelectionCoverage.res","location":"[11:0->11:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.selection","kind":"policy","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false}}]}, + {"coordinate":"SelectionEdge.node","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Structural edge fields are governed by the selection query","file":"src/SelectionCoverage.res","location":"[11:0->11:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.selection","kind":"policy","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false}}]}, + {"coordinate":"SelectionNode.secret","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadSelectionNode","provenance":"field:SelectionNode.secret","file":"src/SelectionCoverage.res","location":"[7:2->7:16]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"SelectionNode.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Value has no authorization identity beyond its selection result","file":"src/SelectionCoverage.res","location":"[2:2->2:27]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.selection","kind":"policy","policy":{"path":"Security.canLoadSelection","provenance":"field:Query.selection","file":"src/Query.res","location":"[47:0->47:14]","async":false}}]}, + {"coordinate":"SharedProtected.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Shared result fields are protected on every entry path","file":"src/AncestorGraph.res","location":"[20:0->20:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Query.firstShared","kind":"policy","policy":{"path":"Security.first","provenance":"field:Query.firstShared","file":"src/AncestorGraph.res","location":"[27:0->27:14]","async":false}},{"coordinate":"Query.secondShared","kind":"policy","policy":{"path":"Security.first","provenance":"field:Query.secondShared","file":"src/AncestorGraph.res","location":"[30:0->30:14]","async":false}}]}, + {"coordinate":"UpdatePayload.value","disposition":"authorizedByAncestor","mutation":false,"policies":[],"public":null,"byAncestor":{"reason":"Mutation payload fields are governed by the mutation policy","file":"src/Mutation.res","location":"[3:0->3:25]"},"resolverOutcome":null,"ancestorBoundaries":[{"coordinate":"Mutation.update","kind":"policy","policy":{"path":"Security.canMutate","provenance":"field:Mutation.update","file":"src/Mutation.res","location":"[10:0->10:14]","async":false}}]}, + {"coordinate":"User.id","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null}, + {"coordinate":"User.secret","disposition":"policies","mutation":false,"policies":[{"path":"Security.canReadUser","provenance":"objectType:User","file":"src/User.res","location":"[0:0->0:14]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:2->4:16]","async":false},{"path":"Security.canReadUser","provenance":"field:User.secret","file":"src/User.res","location":"[4:39->4:53]","async":false}],"public":null,"byAncestor":null,"resolverOutcome":null} ] } diff --git a/tests/authorization/valid/src/AncestorGraph.res b/tests/authorization/valid/src/AncestorGraph.res new file mode 100644 index 00000000..bec2a1cd --- /dev/null +++ b/tests/authorization/valid/src/AncestorGraph.res @@ -0,0 +1,32 @@ +@gql.authorize.byAncestor({reason: "Union member fields are governed by the query policy"}) +@gql.type +type ancestorAlpha = { + @gql.field + value: string, +} + +@gql.authorize.byAncestor({reason: "Union member fields are governed by the query policy"}) +@gql.type +type ancestorBeta = { + @gql.field + value: string, +} + +@gql.union +type ancestorResult = Alpha(ancestorAlpha) | Beta(ancestorBeta) + +@gql.authorize(Security.first) @gql.field +let ancestorUnion = (_: Query.query): ancestorResult => Alpha({value: "alpha"}) + +@gql.authorize.byAncestor({reason: "Shared result fields are protected on every entry path"}) +@gql.type +type sharedProtected = { + @gql.field + value: string, +} + +@gql.authorize(Security.first) @gql.field +let firstShared = (_: Query.query): sharedProtected => {value: "first"} + +@gql.authorize(Security.first) @gql.field +let secondShared = (_: Query.query): sharedProtected => {value: "second"} diff --git a/tests/authorization/valid/src/Mutation.res b/tests/authorization/valid/src/Mutation.res index 66ef186d..724d4725 100644 --- a/tests/authorization/valid/src/Mutation.res +++ b/tests/authorization/valid/src/Mutation.res @@ -1,8 +1,15 @@ @gql.type type mutation +@gql.authorize.byAncestor({reason: "Mutation payload fields are governed by the mutation policy"}) +@gql.type +type updatePayload = { + @gql.field + value: string, +} + @gql.authorize(Security.canMutate) @gql.field -let update = (_: mutation, ~value: string): string => value +let update = (_: mutation, ~value: string): updatePayload => {value: value} @gql.public({reason: "Explicitly public mutation used by uptime checks"}) @gql.field let ping = (_: mutation): bool => true diff --git a/tests/authorization/valid/src/Query.res b/tests/authorization/valid/src/Query.res index 7120ba16..e0d95fa2 100644 --- a/tests/authorization/valid/src/Query.res +++ b/tests/authorization/valid/src/Query.res @@ -45,10 +45,14 @@ type declaredResult = Success({value: string}) | Failure({message: string}) @gql.authorize(Security.first) @gql.field let declared = (_: query): declaredResult => Success({value: "visible"}) -@gql.authorize( - (Security.canLoadSelection, {scope: Fields}) -) -@gql.field +@gql.authorize(Security.canLoadSelection) @gql.field let selection = (_: query): SelectionCoverage.selectionConnection => { - edges: [{cursor: "cursor", node: {value: "selected"}}], + edges: [{cursor: "cursor", node: {value: "selected", secret: "secret"}}], + label: "selection", } + +@gql.field +let outcomePayload = (_: query): ResGraph.Authorization.outcome< + SelectionCoverage.outcomePayload, + string, +> => ResGraph.Authorization.Allowed({value: "outcome protected"}) diff --git a/tests/authorization/valid/src/ResGraph.res b/tests/authorization/valid/src/ResGraph.res index 18f4644f..72b9c403 100644 --- a/tests/authorization/valid/src/ResGraph.res +++ b/tests/authorization/valid/src/ResGraph.res @@ -1,9 +1,6 @@ type resolveInfo = unit module Authorization = { - type scope = Fields - type scopeOptions = {scope: scope} - type outcome<'value, 'reason> = | Allowed('value) | Forbidden('reason) diff --git a/tests/authorization/valid/src/SelectionCoverage.res b/tests/authorization/valid/src/SelectionCoverage.res index 4d857a97..6246f0a2 100644 --- a/tests/authorization/valid/src/SelectionCoverage.res +++ b/tests/authorization/valid/src/SelectionCoverage.res @@ -1,10 +1,15 @@ -@gql.authorize(Security.canReadSelectionNode) @gql.type type selectionNode = { + @gql.authorize.byAncestor({ + reason: "Value has no authorization identity beyond its selection result", + }) @gql.field value: string, + @gql.authorize(Security.canReadSelectionNode) @gql.field + secret: string, } +@gql.authorize.byAncestor({reason: "Structural edge fields are governed by the selection query"}) @gql.type type selectionEdge = { @gql.field @@ -13,8 +18,22 @@ type selectionEdge = { node: selectionNode, } +@gql.authorize.byAncestor({ + reason: "Structural connection fields are governed by the selection query", +}) @gql.type type selectionConnection = { @gql.field edges: array, + @gql.public({reason: "Static label contains no protected data"}) @gql.field + label: string, +} + +@gql.authorize.byAncestor({ + reason: "Payload is exposed only after its resolver outcome allows access", +}) +@gql.type +type outcomePayload = { + @gql.field + value: string, } From 62a5e15f72e78c27ff0b7e942e9c2b6bbd5dcf6a Mon Sep 17 00:00:00 2001 From: Gabriel Nordeborn Date: Sun, 2 Aug 2026 19:26:52 +0200 Subject: [PATCH 4/6] Make manifest upgrade test portable --- tests/authorization/run-tests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/authorization/run-tests.sh b/tests/authorization/run-tests.sh index fa98f702..c6d26fdb 100755 --- a/tests/authorization/run-tests.sh +++ b/tests/authorization/run-tests.sh @@ -85,7 +85,7 @@ jq -e ' mkdir -p "$tmp_dir/manifest-upgrade" cp "$root_dir/tests/authorization/valid/expected-authorization-manifest.json" \ "$tmp_dir/manifest-upgrade/authorization-manifest.json" -sed -i 's/"version": 2/"version": 1/' \ +sed -i.bak 's/"version": 2/"version": 1/' \ "$tmp_dir/manifest-upgrade/authorization-manifest.json" "$resgraph_bin" generate-schema \ "$root_dir/tests/authorization/valid/src" \ From 6c5dadc3b7e8eb9e9a658f1dab1acd9009aa960a Mon Sep 17 00:00:00 2001 From: Gabriel Nordeborn Date: Sun, 2 Aug 2026 19:40:14 +0200 Subject: [PATCH 5/6] Keep subscription paths out of ancestor authorization --- docs/docs/authorization.md | 7 +++++-- src/ml/GenerateSchemaAuthorization.ml | 6 +++++- tests/authorization/invalid/src/Query.res | 5 +++++ tests/authorization/invalid/src/Security.res | 2 ++ tests/authorization/invalid/src/Subscription.res | 15 +++++++++------ .../invalid/src/SubscriptionEvent.res | 6 ++++++ tests/authorization/run-tests.sh | 2 ++ 7 files changed, 34 insertions(+), 9 deletions(-) create mode 100644 tests/authorization/invalid/src/SubscriptionEvent.res diff --git a/docs/docs/authorization.md b/docs/docs/authorization.md index 016e466b..11cc2351 100644 --- a/docs/docs/authorization.md +++ b/docs/docs/authorization.md @@ -130,8 +130,11 @@ field. A public field is not an authorization boundary. If the same object type is reachable through an unprotected path, generation fails at the `byAncestor` annotation. Lists and nullability are transparent to the proof; unions and interface return types fan out to their concrete object types. -`byAncestor` is currently supported on concrete object types and fields, not on -interfaces or subscriptions. +`byAncestor` is currently supported on concrete object types and fields, not +on interfaces or subscription paths. Paths from subscription roots are treated +as unprotected even when the subscription field declares a policy, because +ResGraph cannot yet enforce that policy for each delivered event. Shared return +types therefore cannot hide an unsafe subscription path. The annotation generates no runtime check. Upstream policies run only where they are declared, so expensive authorization is not reevaluated for structural diff --git a/src/ml/GenerateSchemaAuthorization.ml b/src/ml/GenerateSchemaAuthorization.ml index aefea3ff..86fafc83 100644 --- a/src/ml/GenerateSchemaAuthorization.ml +++ b/src/ml/GenerateSchemaAuthorization.ml @@ -678,7 +678,11 @@ let ancestorReachability ~processedSchema (schemaState : schemaState) = ~parentTypeName:typ.displayName ~fieldName:field.name in let plan = Hashtbl.find schemaState.authorizationPlans coordinate in - let localBoundaries = localAuthorizationBoundaries coordinate plan in + let localBoundaries = + if typ.id = "subscription" then + AncestorAuthorizationBoundaries.empty + else localAuthorizationBoundaries coordinate plan + in let outgoing = { hasUnprotectedPath = diff --git a/tests/authorization/invalid/src/Query.res b/tests/authorization/invalid/src/Query.res index da2735d5..a55ee106 100644 --- a/tests/authorization/invalid/src/Query.res +++ b/tests/authorization/invalid/src/Query.res @@ -50,6 +50,11 @@ type sharedSelection = { @gql.authorize(Security.canSelect) @gql.field let protectedSelection = (_: query): sharedSelection => {value: "protected"} +@gql.authorize(Security.canSelect) @gql.field +let protectedSubscriptionEvent = (_: query): SubscriptionEvent.subscriptionEvent => { + value: "protected", +} + @gql.public({reason: "Intentionally exercises an unprotected alternate path"}) @gql.field let publicSelection = (_: query): sharedSelection => {value: "public"} diff --git a/tests/authorization/invalid/src/Security.res b/tests/authorization/invalid/src/Security.res index 216d4b09..a2b24051 100644 --- a/tests/authorization/invalid/src/Security.res +++ b/tests/authorization/invalid/src/Security.res @@ -55,3 +55,5 @@ let nonUnitOutcome = (_: Query.query, ~args: {.}): ResGraph.Authorization.outcom > => ResGraph.Authorization.Allowed("wrong") let canSelect = (_: Query.query, ~args: {.}) => ResGraph.Authorization.Allowed() + +let canSubscribe = (_: Subscription.subscription, ~args: {.}) => ResGraph.Authorization.Allowed() diff --git a/tests/authorization/invalid/src/Subscription.res b/tests/authorization/invalid/src/Subscription.res index 31b93526..17c259e2 100644 --- a/tests/authorization/invalid/src/Subscription.res +++ b/tests/authorization/invalid/src/Subscription.res @@ -1,12 +1,15 @@ @gql.type type subscription -let makeAsyncIterator: (unit => promise>) => AsyncIterator.t< - string, -> = %raw(`function makeAsyncIterator(next) { +let makeAsyncIterator: ( + unit => promise> +) => AsyncIterator.t = %raw(`function makeAsyncIterator(next) { return {next, [Symbol.asyncIterator]() { return this }} }`) -@gql.public({reason: "Still rejected until subscription semantics are defined"}) @gql.field -let events = (_: subscription): AsyncIterator.t => - makeAsyncIterator(async () => {AsyncIterator.done: true, value: Some("event")}) +@gql.authorize(Security.canSubscribe) @gql.field +let events = (_: subscription): AsyncIterator.t => + makeAsyncIterator(async () => { + AsyncIterator.done: true, + value: Some({SubscriptionEvent.value: "event"}), + }) diff --git a/tests/authorization/invalid/src/SubscriptionEvent.res b/tests/authorization/invalid/src/SubscriptionEvent.res new file mode 100644 index 00000000..25ca3680 --- /dev/null +++ b/tests/authorization/invalid/src/SubscriptionEvent.res @@ -0,0 +1,6 @@ +@gql.type +type subscriptionEvent = { + @gql.authorize.byAncestor({reason: "Subscription events require per-event authorization"}) + @gql.field + value: string, +} diff --git a/tests/authorization/run-tests.sh b/tests/authorization/run-tests.sh index c6d26fdb..a6e6ac7a 100755 --- a/tests/authorization/run-tests.sh +++ b/tests/authorization/run-tests.sh @@ -150,6 +150,8 @@ grep -F 'Field `Query.noAncestor` uses `@gql.authorize.byAncestor`' \ "$tmp_dir/invalid-result.json" >/dev/null grep -F 'Field `SharedSelection.value` uses `@gql.authorize.byAncestor`' \ "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Field `SubscriptionEvent.value` uses `@gql.authorize.byAncestor`' \ + "$tmp_dir/invalid-result.json" >/dev/null grep -F '`@gql.authorize.byAncestor` is currently supported on concrete object types' \ "$tmp_dir/invalid-result.json" >/dev/null grep -F 'Required authorization coverage does not support subscription field `Subscription.events` yet.' \ From f388b7743202c836285201f90b45f60c6e04d717 Mon Sep 17 00:00:00 2001 From: Gabriel Nordeborn Date: Sun, 2 Aug 2026 19:48:55 +0200 Subject: [PATCH 6/6] Require mutation policies for ancestor authorization --- docs/docs/authorization.md | 5 +++-- src/ml/GenerateSchemaAuthorization.ml | 20 ++++++++++++-------- tests/authorization/invalid/src/Mutation.res | 10 ++++++++-- tests/authorization/run-tests.sh | 4 ++++ 4 files changed, 27 insertions(+), 12 deletions(-) diff --git a/docs/docs/authorization.md b/docs/docs/authorization.md index 11cc2351..9bb7c31d 100644 --- a/docs/docs/authorization.md +++ b/docs/docs/authorization.md @@ -138,8 +138,9 @@ types therefore cannot hide an unsafe subscription path. The annotation generates no runtime check. Upstream policies run only where they are declared, so expensive authorization is not reevaluated for structural -child fields. Mutation root fields still require a pre-resolver policy; a -payload type may then use `byAncestor`. +child fields. Mutation root fields still require a pre-resolver policy before a +payload type may use `byAncestor`; a mutation's post-resolver outcome does not +serve as that ancestor boundary. ## Resolver outcomes diff --git a/src/ml/GenerateSchemaAuthorization.ml b/src/ml/GenerateSchemaAuthorization.ml index 86fafc83..519be527 100644 --- a/src/ml/GenerateSchemaAuthorization.ml +++ b/src/ml/GenerateSchemaAuthorization.ml @@ -610,18 +610,20 @@ let fieldOutputTypeIds ~processedSchema (schemaState : schemaState) in ids field.typ |> List.sort_uniq String.compare +let localPolicyBoundaries coordinate (plan : effectiveAuthorizationPlan) = + plan.functions + |> List.map (fun fn -> AncestorPolicy {boundaryCoordinate = coordinate; fn}) + |> AncestorAuthorizationBoundaries.of_list + let localAuthorizationBoundaries coordinate (plan : effectiveAuthorizationPlan) = - let boundaries = - plan.functions - |> List.map (fun fn -> AncestorPolicy {boundaryCoordinate = coordinate; fn}) - in + let boundaries = localPolicyBoundaries coordinate plan in match plan.resolverOutcome with - | None -> boundaries |> AncestorAuthorizationBoundaries.of_list + | None -> boundaries | Some outcome -> - AncestorResolverOutcome {boundaryCoordinate = coordinate; outcome} - :: boundaries - |> AncestorAuthorizationBoundaries.of_list + boundaries + |> AncestorAuthorizationBoundaries.add + (AncestorResolverOutcome {boundaryCoordinate = coordinate; outcome}) let updateReachability reachability typeId incoming = match Hashtbl.find_opt reachability typeId with @@ -681,6 +683,8 @@ let ancestorReachability ~processedSchema (schemaState : schemaState) = let localBoundaries = if typ.id = "subscription" then AncestorAuthorizationBoundaries.empty + else if typ.id = "mutation" then + localPolicyBoundaries coordinate plan else localAuthorizationBoundaries coordinate plan in let outgoing = diff --git a/tests/authorization/invalid/src/Mutation.res b/tests/authorization/invalid/src/Mutation.res index 920d3518..39f09afc 100644 --- a/tests/authorization/invalid/src/Mutation.res +++ b/tests/authorization/invalid/src/Mutation.res @@ -1,8 +1,14 @@ @gql.type type mutation +@gql.authorize.byAncestor({reason: "Mutation payloads require a pre-resolver policy"}) @gql.type +type outcomeOnlyPayload = { + @gql.field + value: string, +} + @gql.field let outcomeOnly = (_: mutation): ResGraph.Authorization.outcome< + outcomeOnlyPayload, string, - string, -> => ResGraph.Authorization.Allowed("too late") +> => ResGraph.Authorization.Allowed({value: "too late"}) diff --git a/tests/authorization/run-tests.sh b/tests/authorization/run-tests.sh index a6e6ac7a..c0144c42 100755 --- a/tests/authorization/run-tests.sh +++ b/tests/authorization/run-tests.sh @@ -100,6 +100,8 @@ mkdir -p "$tmp_dir/cache-bypass" "$root_dir/tests/authorization/invalid/src" \ "$tmp_dir/cache-bypass" false \ >"$tmp_dir/cache-bypass-optional-result.json" +grep -F 'Field `OutcomeOnlyPayload.value` uses `@gql.authorize.byAncestor`' \ + "$tmp_dir/cache-bypass-optional-result.json" >/dev/null "$resgraph_bin" generate-schema \ "$root_dir/tests/authorization/invalid/src" \ "$tmp_dir/cache-bypass" false required - \ @@ -129,6 +131,8 @@ grep -F 'must return `ResGraph.Authorization.outcome' \ grep -F 'Public coverage cannot be combined' "$tmp_dir/invalid-result.json" >/dev/null grep -F 'Mutation field `Mutation.outcomeOnly` requires at least one pre-resolver' \ "$tmp_dir/invalid-result.json" >/dev/null +grep -F 'Field `OutcomeOnlyPayload.value` uses `@gql.authorize.byAncestor`' \ + "$tmp_dir/invalid-result.json" >/dev/null grep -F 'Only one `@gql.public` annotation is allowed per field.' \ "$tmp_dir/invalid-result.json" >/dev/null grep -F 'requires a reason with at least 3 non-whitespace characters' \