Skip to content
Snippets Groups Projects
Commit f9e7987f authored by Lyuben Penkovski's avatar Lyuben Penkovski
Browse files

Goa DSL for lock and unlock policy methods

parent aac4f032
No related branches found
No related tags found
1 merge request!3HTTP endpoints for policy lock and unlock
Pipeline #49708 failed with stage
in 1 minute and 9 seconds
Showing
with 726 additions and 29 deletions
......@@ -19,6 +19,7 @@ var _ = Service("policy", func() {
Description("Policy Service provides evaluation of policies through Open Policy Agent.")
Method("Evaluate", func() {
Description("Evaluate executes a policy with the given 'data' as input.")
Payload(EvaluateRequest)
Result(EvaluateResult)
HTTP(func() {
......@@ -26,6 +27,26 @@ var _ = Service("policy", func() {
Response(StatusOK)
})
})
Method("Lock", func() {
Description("Lock a policy so that it cannot be evaluated.")
Payload(LockRequest)
Result(Empty)
HTTP(func() {
POST("/policy/{group}/{policyName}/{version}/lock")
Response(StatusOK)
})
})
Method("Unlock", func() {
Description("Unlock a policy so it can be evaluated again.")
Payload(UnlockRequest)
Result(Empty)
HTTP(func() {
DELETE("/policy/{group}/{policyName}/{version}/lock")
Response(StatusOK)
})
})
})
var _ = Service("health", func() {
......
......@@ -15,3 +15,17 @@ var EvaluateResult = Type("EvaluateResult", func() {
Field(1, "result", Any, "Arbitrary JSON response.")
Required("result")
})
var LockRequest = Type("LockRequest", func() {
Field(1, "group", String, "Policy group")
Field(2, "policyName", String, "Policy name")
Field(3, "version", String, "Policy version")
Required("group", "policyName", "version")
})
var UnlockRequest = Type("UnlockRequest", func() {
Field(1, "group", String, "Policy group")
Field(2, "policyName", String, "Policy name")
Field(3, "version", String, "Policy version")
Required("group", "policyName", "version")
})
......@@ -25,7 +25,7 @@ import (
//
func UsageCommands() string {
return `health (liveness|readiness)
policy evaluate
policy (evaluate|lock|unlock)
`
}
......@@ -33,8 +33,8 @@ policy evaluate
func UsageExamples() string {
return os.Args[0] + ` health liveness` + "\n" +
os.Args[0] + ` policy evaluate --body '{
"data": "Quasi et et laudantium non."
}' --group "Et facilis sit corporis enim." --policy-name "Saepe aut cumque." --version "Ab accusamus voluptatem et est."` + "\n" +
"data": "Id odio aperiam voluptatem molestias corrupti sunt."
}' --group "Ipsum nihil quo." --policy-name "Repellat velit omnis." --version "Vitae qui."` + "\n" +
""
}
......@@ -61,6 +61,16 @@ func ParseEndpoint(
policyEvaluateGroupFlag = policyEvaluateFlags.String("group", "REQUIRED", "Policy group")
policyEvaluatePolicyNameFlag = policyEvaluateFlags.String("policy-name", "REQUIRED", "Policy name")
policyEvaluateVersionFlag = policyEvaluateFlags.String("version", "REQUIRED", "Policy version")
policyLockFlags = flag.NewFlagSet("lock", flag.ExitOnError)
policyLockGroupFlag = policyLockFlags.String("group", "REQUIRED", "Policy group")
policyLockPolicyNameFlag = policyLockFlags.String("policy-name", "REQUIRED", "Policy name")
policyLockVersionFlag = policyLockFlags.String("version", "REQUIRED", "Policy version")
policyUnlockFlags = flag.NewFlagSet("unlock", flag.ExitOnError)
policyUnlockGroupFlag = policyUnlockFlags.String("group", "REQUIRED", "Policy group")
policyUnlockPolicyNameFlag = policyUnlockFlags.String("policy-name", "REQUIRED", "Policy name")
policyUnlockVersionFlag = policyUnlockFlags.String("version", "REQUIRED", "Policy version")
)
healthFlags.Usage = healthUsage
healthLivenessFlags.Usage = healthLivenessUsage
......@@ -68,6 +78,8 @@ func ParseEndpoint(
policyFlags.Usage = policyUsage
policyEvaluateFlags.Usage = policyEvaluateUsage
policyLockFlags.Usage = policyLockUsage
policyUnlockFlags.Usage = policyUnlockUsage
if err := flag.CommandLine.Parse(os.Args[1:]); err != nil {
return nil, nil, err
......@@ -118,6 +130,12 @@ func ParseEndpoint(
case "evaluate":
epf = policyEvaluateFlags
case "lock":
epf = policyLockFlags
case "unlock":
epf = policyUnlockFlags
}
}
......@@ -156,6 +174,12 @@ func ParseEndpoint(
case "evaluate":
endpoint = c.Evaluate()
data, err = policyc.BuildEvaluatePayload(*policyEvaluateBodyFlag, *policyEvaluateGroupFlag, *policyEvaluatePolicyNameFlag, *policyEvaluateVersionFlag)
case "lock":
endpoint = c.Lock()
data, err = policyc.BuildLockPayload(*policyLockGroupFlag, *policyLockPolicyNameFlag, *policyLockVersionFlag)
case "unlock":
endpoint = c.Unlock()
data, err = policyc.BuildUnlockPayload(*policyUnlockGroupFlag, *policyUnlockPolicyNameFlag, *policyUnlockVersionFlag)
}
}
}
......@@ -207,7 +231,9 @@ Usage:
%[1]s [globalflags] policy COMMAND [flags]
COMMAND:
evaluate: Evaluate implements Evaluate.
evaluate: Evaluate executes a policy with the given 'data' as input.
lock: Lock a policy so that it cannot be evaluated.
unlock: Unlock a policy so it can be evaluated again.
Additional help:
%[1]s policy COMMAND --help
......@@ -216,7 +242,7 @@ Additional help:
func policyEvaluateUsage() {
fmt.Fprintf(os.Stderr, `%[1]s [flags] policy evaluate -body JSON -group STRING -policy-name STRING -version STRING
Evaluate implements Evaluate.
Evaluate executes a policy with the given 'data' as input.
-body JSON:
-group STRING: Policy group
-policy-name STRING: Policy name
......@@ -224,7 +250,33 @@ Evaluate implements Evaluate.
Example:
%[1]s policy evaluate --body '{
"data": "Quasi et et laudantium non."
}' --group "Et facilis sit corporis enim." --policy-name "Saepe aut cumque." --version "Ab accusamus voluptatem et est."
"data": "Id odio aperiam voluptatem molestias corrupti sunt."
}' --group "Ipsum nihil quo." --policy-name "Repellat velit omnis." --version "Vitae qui."
`, os.Args[0])
}
func policyLockUsage() {
fmt.Fprintf(os.Stderr, `%[1]s [flags] policy lock -group STRING -policy-name STRING -version STRING
Lock a policy so that it cannot be evaluated.
-group STRING: Policy group
-policy-name STRING: Policy name
-version STRING: Policy version
Example:
%[1]s policy lock --group "Repudiandae dolore quod." --policy-name "Aut ut fuga quae eius minus." --version "Architecto quibusdam ab."
`, os.Args[0])
}
func policyUnlockUsage() {
fmt.Fprintf(os.Stderr, `%[1]s [flags] policy unlock -group STRING -policy-name STRING -version STRING
Unlock a policy so it can be evaluated again.
-group STRING: Policy group
-policy-name STRING: Policy name
-version STRING: Policy version
Example:
%[1]s policy unlock --group "Omnis quasi aut consequuntur." --policy-name "Tempore minus." --version "Quis quos qui earum velit illum."
`, os.Args[0])
}
{"swagger":"2.0","info":{"title":"Policy Service","description":"The policy service exposes HTTP API for executing policies.","version":""},"host":"localhost:8080","consumes":["application/json","application/xml","application/gob"],"produces":["application/json","application/xml","application/gob"],"paths":{"/liveness":{"get":{"tags":["health"],"summary":"Liveness health","operationId":"health#Liveness","responses":{"200":{"description":"OK response."}},"schemes":["http"]}},"/policy/{group}/{policyName}/{version}/evaluation":{"post":{"tags":["policy"],"summary":"Evaluate policy","operationId":"policy#Evaluate","parameters":[{"name":"group","in":"path","description":"Policy group","required":true,"type":"string"},{"name":"policyName","in":"path","description":"Policy name","required":true,"type":"string"},{"name":"version","in":"path","description":"Policy version","required":true,"type":"string"},{"name":"EvaluateRequestBody","in":"body","required":true,"schema":{"$ref":"#/definitions/PolicyEvaluateRequestBody","required":["data"]}}],"responses":{"200":{"description":"OK response.","schema":{"$ref":"#/definitions/PolicyEvaluateResponseBody","required":["result"]}}},"schemes":["http"]}},"/readiness":{"get":{"tags":["health"],"summary":"Readiness health","operationId":"health#Readiness","responses":{"200":{"description":"OK response."}},"schemes":["http"]}}},"definitions":{"PolicyEvaluateRequestBody":{"title":"PolicyEvaluateRequestBody","type":"object","properties":{"data":{"type":"string","description":"Data passed as input to the policy execution runtime","example":"Ipsum nihil quo.","format":"binary"}},"example":{"data":"Repellat velit omnis."},"required":["data"]},"PolicyEvaluateResponseBody":{"title":"PolicyEvaluateResponseBody","type":"object","properties":{"result":{"type":"string","description":"Arbitrary JSON response.","example":"Illum ad assumenda consectetur minima voluptatibus.","format":"binary"}},"example":{"result":"Id odio aperiam voluptatem molestias corrupti sunt."},"required":["result"]}}}
\ No newline at end of file
{"swagger":"2.0","info":{"title":"Policy Service","description":"The policy service exposes HTTP API for executing policies.","version":""},"host":"localhost:8080","consumes":["application/json","application/xml","application/gob"],"produces":["application/json","application/xml","application/gob"],"paths":{"/liveness":{"get":{"tags":["health"],"summary":"Liveness health","operationId":"health#Liveness","responses":{"200":{"description":"OK response."}},"schemes":["http"]}},"/policy/{group}/{policyName}/{version}/evaluation":{"post":{"tags":["policy"],"summary":"Evaluate policy","description":"Evaluate executes a policy with the given 'data' as input.","operationId":"policy#Evaluate","parameters":[{"name":"group","in":"path","description":"Policy group","required":true,"type":"string"},{"name":"policyName","in":"path","description":"Policy name","required":true,"type":"string"},{"name":"version","in":"path","description":"Policy version","required":true,"type":"string"},{"name":"EvaluateRequestBody","in":"body","required":true,"schema":{"$ref":"#/definitions/PolicyEvaluateRequestBody","required":["data"]}}],"responses":{"200":{"description":"OK response.","schema":{"$ref":"#/definitions/PolicyEvaluateResponseBody","required":["result"]}}},"schemes":["http"]}},"/policy/{group}/{policyName}/{version}/lock":{"post":{"tags":["policy"],"summary":"Lock policy","description":"Lock a policy so that it cannot be evaluated.","operationId":"policy#Lock","parameters":[{"name":"group","in":"path","description":"Policy group","required":true,"type":"string"},{"name":"policyName","in":"path","description":"Policy name","required":true,"type":"string"},{"name":"version","in":"path","description":"Policy version","required":true,"type":"string"}],"responses":{"200":{"description":"OK response."}},"schemes":["http"]},"delete":{"tags":["policy"],"summary":"Unlock policy","description":"Unlock a policy so it can be evaluated again.","operationId":"policy#Unlock","parameters":[{"name":"group","in":"path","description":"Policy group","required":true,"type":"string"},{"name":"policyName","in":"path","description":"Policy name","required":true,"type":"string"},{"name":"version","in":"path","description":"Policy version","required":true,"type":"string"}],"responses":{"200":{"description":"OK response."}},"schemes":["http"]}},"/readiness":{"get":{"tags":["health"],"summary":"Readiness health","operationId":"health#Readiness","responses":{"200":{"description":"OK response."}},"schemes":["http"]}}},"definitions":{"PolicyEvaluateRequestBody":{"title":"PolicyEvaluateRequestBody","type":"object","properties":{"data":{"type":"string","description":"Data passed as input to the policy execution runtime","example":"Aut minus alias.","format":"binary"}},"example":{"data":"At eos facilis molestias in voluptas rem."},"required":["data"]},"PolicyEvaluateResponseBody":{"title":"PolicyEvaluateResponseBody","type":"object","properties":{"result":{"type":"string","description":"Arbitrary JSON response.","example":"Aliquam atque voluptatum ut dolorem.","format":"binary"}},"example":{"result":"Aut facere veniam repudiandae id."},"required":["result"]}}}
\ No newline at end of file
......@@ -29,6 +29,7 @@ paths:
tags:
- policy
summary: Evaluate policy
description: Evaluate executes a policy with the given 'data' as input.
operationId: policy#Evaluate
parameters:
- name: group
......@@ -62,6 +63,61 @@ paths:
- result
schemes:
- http
/policy/{group}/{policyName}/{version}/lock:
post:
tags:
- policy
summary: Lock policy
description: Lock a policy so that it cannot be evaluated.
operationId: policy#Lock
parameters:
- name: group
in: path
description: Policy group
required: true
type: string
- name: policyName
in: path
description: Policy name
required: true
type: string
- name: version
in: path
description: Policy version
required: true
type: string
responses:
"200":
description: OK response.
schemes:
- http
delete:
tags:
- policy
summary: Unlock policy
description: Unlock a policy so it can be evaluated again.
operationId: policy#Unlock
parameters:
- name: group
in: path
description: Policy group
required: true
type: string
- name: policyName
in: path
description: Policy name
required: true
type: string
- name: version
in: path
description: Policy version
required: true
type: string
responses:
"200":
description: OK response.
schemes:
- http
/readiness:
get:
tags:
......@@ -81,10 +137,10 @@ definitions:
data:
type: string
description: Data passed as input to the policy execution runtime
example: Ipsum nihil quo.
example: Aut minus alias.
format: binary
example:
data: Repellat velit omnis.
data: At eos facilis molestias in voluptas rem.
required:
- data
PolicyEvaluateResponseBody:
......@@ -94,9 +150,9 @@ definitions:
result:
type: string
description: Arbitrary JSON response.
example: Illum ad assumenda consectetur minima voluptatibus.
example: Aliquam atque voluptatum ut dolorem.
format: binary
example:
result: Id odio aperiam voluptatem molestias corrupti sunt.
result: Aut facere veniam repudiandae id.
required:
- result
{"openapi":"3.0.3","info":{"title":"Policy Service","description":"The policy service exposes HTTP API for executing policies.","version":"1.0"},"servers":[{"url":"http://localhost:8080","description":"Policy Server"}],"paths":{"/liveness":{"get":{"tags":["health"],"summary":"Liveness health","operationId":"health#Liveness","responses":{"200":{"description":"OK response."}}}},"/policy/{group}/{policyName}/{version}/evaluation":{"post":{"tags":["policy"],"summary":"Evaluate policy","operationId":"policy#Evaluate","parameters":[{"name":"group","in":"path","description":"Policy group","required":true,"schema":{"type":"string","description":"Policy group","example":"Explicabo beatae quisquam officiis libero voluptatibus."},"example":"Repudiandae dolore quod."},{"name":"policyName","in":"path","description":"Policy name","required":true,"schema":{"type":"string","description":"Policy name","example":"Aut ut fuga quae eius minus."},"example":"Architecto quibusdam ab."},{"name":"version","in":"path","description":"Policy version","required":true,"schema":{"type":"string","description":"Policy version","example":"In illum est et hic."},"example":"Deleniti non nihil dolor aut sed."}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EvaluateRequestBody"},"example":{"data":"Quasi et et laudantium non."}}}},"responses":{"200":{"description":"OK response.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EvaluateResult"},"example":{"result":"Et voluptates."}}}}}}},"/readiness":{"get":{"tags":["health"],"summary":"Readiness health","operationId":"health#Readiness","responses":{"200":{"description":"OK response."}}}}},"components":{"schemas":{"EvaluateRequestBody":{"type":"object","properties":{"data":{"type":"string","description":"Data passed as input to the policy execution runtime","example":"Vitae qui.","format":"binary"}},"example":{"data":"Provident fugiat at cupiditate."},"required":["data"]},"EvaluateResult":{"type":"object","properties":{"result":{"type":"string","description":"Arbitrary JSON response.","example":"Commodi vitae voluptatem.","format":"binary"}},"example":{"result":"Similique quisquam optio."},"required":["result"]}}},"tags":[{"name":"health","description":"Health service provides health check endpoints."},{"name":"policy","description":"Policy Service provides evaluation of policies through Open Policy Agent."}]}
\ No newline at end of file
{"openapi":"3.0.3","info":{"title":"Policy Service","description":"The policy service exposes HTTP API for executing policies.","version":"1.0"},"servers":[{"url":"http://localhost:8080","description":"Policy Server"}],"paths":{"/liveness":{"get":{"tags":["health"],"summary":"Liveness health","operationId":"health#Liveness","responses":{"200":{"description":"OK response."}}}},"/policy/{group}/{policyName}/{version}/evaluation":{"post":{"tags":["policy"],"summary":"Evaluate policy","description":"Evaluate executes a policy with the given 'data' as input.","operationId":"policy#Evaluate","parameters":[{"name":"group","in":"path","description":"Policy group","required":true,"schema":{"type":"string","description":"Policy group","example":"Non mollitia nesciunt impedit facere."},"example":"Ut commodi perspiciatis corporis."},{"name":"policyName","in":"path","description":"Policy name","required":true,"schema":{"type":"string","description":"Policy name","example":"Accusamus autem sequi."},"example":"Et nulla."},{"name":"version","in":"path","description":"Policy version","required":true,"schema":{"type":"string","description":"Policy version","example":"In quis nesciunt autem et."},"example":"Sunt in et quia cum."}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EvaluateRequestBody"},"example":{"data":"Id odio aperiam voluptatem molestias corrupti sunt."}}}},"responses":{"200":{"description":"OK response.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EvaluateResult"},"example":{"result":"Provident fugiat at cupiditate."}}}}}}},"/policy/{group}/{policyName}/{version}/lock":{"delete":{"tags":["policy"],"summary":"Unlock policy","description":"Unlock a policy so it can be evaluated again.","operationId":"policy#Unlock","parameters":[{"name":"group","in":"path","description":"Policy group","required":true,"schema":{"type":"string","description":"Policy group","example":"Accusamus enim."},"example":"Recusandae est rerum corrupti quia."},{"name":"policyName","in":"path","description":"Policy name","required":true,"schema":{"type":"string","description":"Policy name","example":"Quam dolores architecto itaque."},"example":"Voluptas ad corporis adipisci inventore ipsum."},{"name":"version","in":"path","description":"Policy version","required":true,"schema":{"type":"string","description":"Policy version","example":"Recusandae dolorum nisi distinctio vitae ad."},"example":"Perspiciatis voluptatem."}],"responses":{"200":{"description":"OK response."}}},"post":{"tags":["policy"],"summary":"Lock policy","description":"Lock a policy so that it cannot be evaluated.","operationId":"policy#Lock","parameters":[{"name":"group","in":"path","description":"Policy group","required":true,"schema":{"type":"string","description":"Policy group","example":"Commodi nemo fugiat id praesentium accusantium expedita."},"example":"Qui non quia."},{"name":"policyName","in":"path","description":"Policy name","required":true,"schema":{"type":"string","description":"Policy name","example":"Error maxime quasi quia non voluptatibus error."},"example":"Optio quia et laborum."},{"name":"version","in":"path","description":"Policy version","required":true,"schema":{"type":"string","description":"Policy version","example":"In libero perspiciatis voluptatum ut soluta."},"example":"Ut amet."}],"responses":{"200":{"description":"OK response."}}}},"/readiness":{"get":{"tags":["health"],"summary":"Readiness health","operationId":"health#Readiness","responses":{"200":{"description":"OK response."}}}}},"components":{"schemas":{"EvaluateRequestBody":{"type":"object","properties":{"data":{"type":"string","description":"Data passed as input to the policy execution runtime","example":"Ab accusantium ut ut aliquid sint animi.","format":"binary"}},"example":{"data":"Dolorem cumque laborum quis nesciunt."},"required":["data"]},"EvaluateResult":{"type":"object","properties":{"result":{"type":"string","description":"Arbitrary JSON response.","example":"Aut voluptas.","format":"binary"}},"example":{"result":"Sint nam voluptatem ea consequatur similique et."},"required":["result"]}}},"tags":[{"name":"health","description":"Health service provides health check endpoints."},{"name":"policy","description":"Policy Service provides evaluation of policies through Open Policy Agent."}]}
\ No newline at end of file
......@@ -21,6 +21,7 @@ paths:
tags:
- policy
summary: Evaluate policy
description: Evaluate executes a policy with the given 'data' as input.
operationId: policy#Evaluate
parameters:
- name: group
......@@ -30,8 +31,8 @@ paths:
schema:
type: string
description: Policy group
example: Explicabo beatae quisquam officiis libero voluptatibus.
example: Repudiandae dolore quod.
example: Non mollitia nesciunt impedit facere.
example: Ut commodi perspiciatis corporis.
- name: policyName
in: path
description: Policy name
......@@ -39,8 +40,8 @@ paths:
schema:
type: string
description: Policy name
example: Aut ut fuga quae eius minus.
example: Architecto quibusdam ab.
example: Accusamus autem sequi.
example: Et nulla.
- name: version
in: path
description: Policy version
......@@ -48,8 +49,8 @@ paths:
schema:
type: string
description: Policy version
example: In illum est et hic.
example: Deleniti non nihil dolor aut sed.
example: In quis nesciunt autem et.
example: Sunt in et quia cum.
requestBody:
required: true
content:
......@@ -57,7 +58,7 @@ paths:
schema:
$ref: '#/components/schemas/EvaluateRequestBody'
example:
data: Quasi et et laudantium non.
data: Id odio aperiam voluptatem molestias corrupti sunt.
responses:
"200":
description: OK response.
......@@ -66,7 +67,82 @@ paths:
schema:
$ref: '#/components/schemas/EvaluateResult'
example:
result: Et voluptates.
result: Provident fugiat at cupiditate.
/policy/{group}/{policyName}/{version}/lock:
delete:
tags:
- policy
summary: Unlock policy
description: Unlock a policy so it can be evaluated again.
operationId: policy#Unlock
parameters:
- name: group
in: path
description: Policy group
required: true
schema:
type: string
description: Policy group
example: Accusamus enim.
example: Recusandae est rerum corrupti quia.
- name: policyName
in: path
description: Policy name
required: true
schema:
type: string
description: Policy name
example: Quam dolores architecto itaque.
example: Voluptas ad corporis adipisci inventore ipsum.
- name: version
in: path
description: Policy version
required: true
schema:
type: string
description: Policy version
example: Recusandae dolorum nisi distinctio vitae ad.
example: Perspiciatis voluptatem.
responses:
"200":
description: OK response.
post:
tags:
- policy
summary: Lock policy
description: Lock a policy so that it cannot be evaluated.
operationId: policy#Lock
parameters:
- name: group
in: path
description: Policy group
required: true
schema:
type: string
description: Policy group
example: Commodi nemo fugiat id praesentium accusantium expedita.
example: Qui non quia.
- name: policyName
in: path
description: Policy name
required: true
schema:
type: string
description: Policy name
example: Error maxime quasi quia non voluptatibus error.
example: Optio quia et laborum.
- name: version
in: path
description: Policy version
required: true
schema:
type: string
description: Policy version
example: In libero perspiciatis voluptatum ut soluta.
example: Ut amet.
responses:
"200":
description: OK response.
/readiness:
get:
tags:
......@@ -84,10 +160,10 @@ components:
data:
type: string
description: Data passed as input to the policy execution runtime
example: Vitae qui.
example: Ab accusantium ut ut aliquid sint animi.
format: binary
example:
data: Provident fugiat at cupiditate.
data: Dolorem cumque laborum quis nesciunt.
required:
- data
EvaluateResult:
......@@ -96,10 +172,10 @@ components:
result:
type: string
description: Arbitrary JSON response.
example: Commodi vitae voluptatem.
example: Aut voluptas.
format: binary
example:
result: Similique quisquam optio.
result: Sint nam voluptatem ea consequatur similique et.
required:
- result
tags:
......
......@@ -23,7 +23,7 @@ func BuildEvaluatePayload(policyEvaluateBody string, policyEvaluateGroup string,
{
err = json.Unmarshal([]byte(policyEvaluateBody), &body)
if err != nil {
return nil, fmt.Errorf("invalid JSON for body, \nerror: %s, \nexample of valid JSON:\n%s", err, "'{\n \"data\": \"Quasi et et laudantium non.\"\n }'")
return nil, fmt.Errorf("invalid JSON for body, \nerror: %s, \nexample of valid JSON:\n%s", err, "'{\n \"data\": \"Id odio aperiam voluptatem molestias corrupti sunt.\"\n }'")
}
if body.Data == nil {
err = goa.MergeErrors(err, goa.MissingFieldError("data", "body"))
......@@ -53,3 +53,49 @@ func BuildEvaluatePayload(policyEvaluateBody string, policyEvaluateGroup string,
return v, nil
}
// BuildLockPayload builds the payload for the policy Lock endpoint from CLI
// flags.
func BuildLockPayload(policyLockGroup string, policyLockPolicyName string, policyLockVersion string) (*policy.LockRequest, error) {
var group string
{
group = policyLockGroup
}
var policyName string
{
policyName = policyLockPolicyName
}
var version string
{
version = policyLockVersion
}
v := &policy.LockRequest{}
v.Group = group
v.PolicyName = policyName
v.Version = version
return v, nil
}
// BuildUnlockPayload builds the payload for the policy Unlock endpoint from
// CLI flags.
func BuildUnlockPayload(policyUnlockGroup string, policyUnlockPolicyName string, policyUnlockVersion string) (*policy.UnlockRequest, error) {
var group string
{
group = policyUnlockGroup
}
var policyName string
{
policyName = policyUnlockPolicyName
}
var version string
{
version = policyUnlockVersion
}
v := &policy.UnlockRequest{}
v.Group = group
v.PolicyName = policyName
v.Version = version
return v, nil
}
......@@ -21,6 +21,12 @@ type Client struct {
// endpoint.
EvaluateDoer goahttp.Doer
// Lock Doer is the HTTP client used to make requests to the Lock endpoint.
LockDoer goahttp.Doer
// Unlock Doer is the HTTP client used to make requests to the Unlock endpoint.
UnlockDoer goahttp.Doer
// RestoreResponseBody controls whether the response bodies are reset after
// decoding so they can be read again.
RestoreResponseBody bool
......@@ -42,6 +48,8 @@ func NewClient(
) *Client {
return &Client{
EvaluateDoer: doer,
LockDoer: doer,
UnlockDoer: doer,
RestoreResponseBody: restoreBody,
scheme: scheme,
host: host,
......@@ -73,3 +81,41 @@ func (c *Client) Evaluate() goa.Endpoint {
return decodeResponse(resp)
}
}
// Lock returns an endpoint that makes HTTP requests to the policy service Lock
// server.
func (c *Client) Lock() goa.Endpoint {
var (
decodeResponse = DecodeLockResponse(c.decoder, c.RestoreResponseBody)
)
return func(ctx context.Context, v interface{}) (interface{}, error) {
req, err := c.BuildLockRequest(ctx, v)
if err != nil {
return nil, err
}
resp, err := c.LockDoer.Do(req)
if err != nil {
return nil, goahttp.ErrRequestError("policy", "Lock", err)
}
return decodeResponse(resp)
}
}
// Unlock returns an endpoint that makes HTTP requests to the policy service
// Unlock server.
func (c *Client) Unlock() goa.Endpoint {
var (
decodeResponse = DecodeUnlockResponse(c.decoder, c.RestoreResponseBody)
)
return func(ctx context.Context, v interface{}) (interface{}, error) {
req, err := c.BuildUnlockRequest(ctx, v)
if err != nil {
return nil, err
}
resp, err := c.UnlockDoer.Do(req)
if err != nil {
return nil, goahttp.ErrRequestError("policy", "Unlock", err)
}
return decodeResponse(resp)
}
}
......@@ -102,3 +102,115 @@ func DecodeEvaluateResponse(decoder func(*http.Response) goahttp.Decoder, restor
}
}
}
// BuildLockRequest instantiates a HTTP request object with method and path set
// to call the "policy" service "Lock" endpoint
func (c *Client) BuildLockRequest(ctx context.Context, v interface{}) (*http.Request, error) {
var (
group string
policyName string
version string
)
{
p, ok := v.(*policy.LockRequest)
if !ok {
return nil, goahttp.ErrInvalidType("policy", "Lock", "*policy.LockRequest", v)
}
group = p.Group
policyName = p.PolicyName
version = p.Version
}
u := &url.URL{Scheme: c.scheme, Host: c.host, Path: LockPolicyPath(group, policyName, version)}
req, err := http.NewRequest("POST", u.String(), nil)
if err != nil {
return nil, goahttp.ErrInvalidURL("policy", "Lock", u.String(), err)
}
if ctx != nil {
req = req.WithContext(ctx)
}
return req, nil
}
// DecodeLockResponse returns a decoder for responses returned by the policy
// Lock endpoint. restoreBody controls whether the response body should be
// restored after having been read.
func DecodeLockResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (interface{}, error) {
return func(resp *http.Response) (interface{}, error) {
if restoreBody {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
resp.Body = ioutil.NopCloser(bytes.NewBuffer(b))
defer func() {
resp.Body = ioutil.NopCloser(bytes.NewBuffer(b))
}()
} else {
defer resp.Body.Close()
}
switch resp.StatusCode {
case http.StatusOK:
return nil, nil
default:
body, _ := ioutil.ReadAll(resp.Body)
return nil, goahttp.ErrInvalidResponse("policy", "Lock", resp.StatusCode, string(body))
}
}
}
// BuildUnlockRequest instantiates a HTTP request object with method and path
// set to call the "policy" service "Unlock" endpoint
func (c *Client) BuildUnlockRequest(ctx context.Context, v interface{}) (*http.Request, error) {
var (
group string
policyName string
version string
)
{
p, ok := v.(*policy.UnlockRequest)
if !ok {
return nil, goahttp.ErrInvalidType("policy", "Unlock", "*policy.UnlockRequest", v)
}
group = p.Group
policyName = p.PolicyName
version = p.Version
}
u := &url.URL{Scheme: c.scheme, Host: c.host, Path: UnlockPolicyPath(group, policyName, version)}
req, err := http.NewRequest("DELETE", u.String(), nil)
if err != nil {
return nil, goahttp.ErrInvalidURL("policy", "Unlock", u.String(), err)
}
if ctx != nil {
req = req.WithContext(ctx)
}
return req, nil
}
// DecodeUnlockResponse returns a decoder for responses returned by the policy
// Unlock endpoint. restoreBody controls whether the response body should be
// restored after having been read.
func DecodeUnlockResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (interface{}, error) {
return func(resp *http.Response) (interface{}, error) {
if restoreBody {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
resp.Body = ioutil.NopCloser(bytes.NewBuffer(b))
defer func() {
resp.Body = ioutil.NopCloser(bytes.NewBuffer(b))
}()
} else {
defer resp.Body.Close()
}
switch resp.StatusCode {
case http.StatusOK:
return nil, nil
default:
body, _ := ioutil.ReadAll(resp.Body)
return nil, goahttp.ErrInvalidResponse("policy", "Unlock", resp.StatusCode, string(body))
}
}
}
......@@ -15,3 +15,13 @@ import (
func EvaluatePolicyPath(group string, policyName string, version string) string {
return fmt.Sprintf("/policy/%v/%v/%v/evaluation", group, policyName, version)
}
// LockPolicyPath returns the URL path to the policy service Lock HTTP endpoint.
func LockPolicyPath(group string, policyName string, version string) string {
return fmt.Sprintf("/policy/%v/%v/%v/lock", group, policyName, version)
}
// UnlockPolicyPath returns the URL path to the policy service Unlock HTTP endpoint.
func UnlockPolicyPath(group string, policyName string, version string) string {
return fmt.Sprintf("/policy/%v/%v/%v/lock", group, policyName, version)
}
......@@ -64,3 +64,61 @@ func DecodeEvaluateRequest(mux goahttp.Muxer, decoder func(*http.Request) goahtt
return payload, nil
}
}
// EncodeLockResponse returns an encoder for responses returned by the policy
// Lock endpoint.
func EncodeLockResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, interface{}) error {
return func(ctx context.Context, w http.ResponseWriter, v interface{}) error {
w.WriteHeader(http.StatusOK)
return nil
}
}
// DecodeLockRequest returns a decoder for requests sent to the policy Lock
// endpoint.
func DecodeLockRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (interface{}, error) {
return func(r *http.Request) (interface{}, error) {
var (
group string
policyName string
version string
params = mux.Vars(r)
)
group = params["group"]
policyName = params["policyName"]
version = params["version"]
payload := NewLockRequest(group, policyName, version)
return payload, nil
}
}
// EncodeUnlockResponse returns an encoder for responses returned by the policy
// Unlock endpoint.
func EncodeUnlockResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, interface{}) error {
return func(ctx context.Context, w http.ResponseWriter, v interface{}) error {
w.WriteHeader(http.StatusOK)
return nil
}
}
// DecodeUnlockRequest returns a decoder for requests sent to the policy Unlock
// endpoint.
func DecodeUnlockRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (interface{}, error) {
return func(r *http.Request) (interface{}, error) {
var (
group string
policyName string
version string
params = mux.Vars(r)
)
group = params["group"]
policyName = params["policyName"]
version = params["version"]
payload := NewUnlockRequest(group, policyName, version)
return payload, nil
}
}
......@@ -15,3 +15,13 @@ import (
func EvaluatePolicyPath(group string, policyName string, version string) string {
return fmt.Sprintf("/policy/%v/%v/%v/evaluation", group, policyName, version)
}
// LockPolicyPath returns the URL path to the policy service Lock HTTP endpoint.
func LockPolicyPath(group string, policyName string, version string) string {
return fmt.Sprintf("/policy/%v/%v/%v/lock", group, policyName, version)
}
// UnlockPolicyPath returns the URL path to the policy service Unlock HTTP endpoint.
func UnlockPolicyPath(group string, policyName string, version string) string {
return fmt.Sprintf("/policy/%v/%v/%v/lock", group, policyName, version)
}
......@@ -20,6 +20,8 @@ import (
type Server struct {
Mounts []*MountPoint
Evaluate http.Handler
Lock http.Handler
Unlock http.Handler
}
// ErrorNamer is an interface implemented by generated error structs that
......@@ -56,8 +58,12 @@ func New(
return &Server{
Mounts: []*MountPoint{
{"Evaluate", "POST", "/policy/{group}/{policyName}/{version}/evaluation"},
{"Lock", "POST", "/policy/{group}/{policyName}/{version}/lock"},
{"Unlock", "DELETE", "/policy/{group}/{policyName}/{version}/lock"},
},
Evaluate: NewEvaluateHandler(e.Evaluate, mux, decoder, encoder, errhandler, formatter),
Lock: NewLockHandler(e.Lock, mux, decoder, encoder, errhandler, formatter),
Unlock: NewUnlockHandler(e.Unlock, mux, decoder, encoder, errhandler, formatter),
}
}
......@@ -67,11 +73,15 @@ func (s *Server) Service() string { return "policy" }
// Use wraps the server handlers with the given middleware.
func (s *Server) Use(m func(http.Handler) http.Handler) {
s.Evaluate = m(s.Evaluate)
s.Lock = m(s.Lock)
s.Unlock = m(s.Unlock)
}
// Mount configures the mux to serve the policy endpoints.
func Mount(mux goahttp.Muxer, h *Server) {
MountEvaluateHandler(mux, h.Evaluate)
MountLockHandler(mux, h.Lock)
MountUnlockHandler(mux, h.Unlock)
}
// Mount configures the mux to serve the policy endpoints.
......@@ -129,3 +139,105 @@ func NewEvaluateHandler(
}
})
}
// MountLockHandler configures the mux to serve the "policy" service "Lock"
// endpoint.
func MountLockHandler(mux goahttp.Muxer, h http.Handler) {
f, ok := h.(http.HandlerFunc)
if !ok {
f = func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
}
}
mux.Handle("POST", "/policy/{group}/{policyName}/{version}/lock", f)
}
// NewLockHandler creates a HTTP handler which loads the HTTP request and calls
// the "policy" service "Lock" endpoint.
func NewLockHandler(
endpoint goa.Endpoint,
mux goahttp.Muxer,
decoder func(*http.Request) goahttp.Decoder,
encoder func(context.Context, http.ResponseWriter) goahttp.Encoder,
errhandler func(context.Context, http.ResponseWriter, error),
formatter func(err error) goahttp.Statuser,
) http.Handler {
var (
decodeRequest = DecodeLockRequest(mux, decoder)
encodeResponse = EncodeLockResponse(encoder)
encodeError = goahttp.ErrorEncoder(encoder, formatter)
)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), goahttp.AcceptTypeKey, r.Header.Get("Accept"))
ctx = context.WithValue(ctx, goa.MethodKey, "Lock")
ctx = context.WithValue(ctx, goa.ServiceKey, "policy")
payload, err := decodeRequest(r)
if err != nil {
if err := encodeError(ctx, w, err); err != nil {
errhandler(ctx, w, err)
}
return
}
res, err := endpoint(ctx, payload)
if err != nil {
if err := encodeError(ctx, w, err); err != nil {
errhandler(ctx, w, err)
}
return
}
if err := encodeResponse(ctx, w, res); err != nil {
errhandler(ctx, w, err)
}
})
}
// MountUnlockHandler configures the mux to serve the "policy" service "Unlock"
// endpoint.
func MountUnlockHandler(mux goahttp.Muxer, h http.Handler) {
f, ok := h.(http.HandlerFunc)
if !ok {
f = func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
}
}
mux.Handle("DELETE", "/policy/{group}/{policyName}/{version}/lock", f)
}
// NewUnlockHandler creates a HTTP handler which loads the HTTP request and
// calls the "policy" service "Unlock" endpoint.
func NewUnlockHandler(
endpoint goa.Endpoint,
mux goahttp.Muxer,
decoder func(*http.Request) goahttp.Decoder,
encoder func(context.Context, http.ResponseWriter) goahttp.Encoder,
errhandler func(context.Context, http.ResponseWriter, error),
formatter func(err error) goahttp.Statuser,
) http.Handler {
var (
decodeRequest = DecodeUnlockRequest(mux, decoder)
encodeResponse = EncodeUnlockResponse(encoder)
encodeError = goahttp.ErrorEncoder(encoder, formatter)
)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), goahttp.AcceptTypeKey, r.Header.Get("Accept"))
ctx = context.WithValue(ctx, goa.MethodKey, "Unlock")
ctx = context.WithValue(ctx, goa.ServiceKey, "policy")
payload, err := decodeRequest(r)
if err != nil {
if err := encodeError(ctx, w, err); err != nil {
errhandler(ctx, w, err)
}
return
}
res, err := endpoint(ctx, payload)
if err != nil {
if err := encodeError(ctx, w, err); err != nil {
errhandler(ctx, w, err)
}
return
}
if err := encodeResponse(ctx, w, res); err != nil {
errhandler(ctx, w, err)
}
})
}
......@@ -47,6 +47,26 @@ func NewEvaluateRequest(body *EvaluateRequestBody, group string, policyName stri
return v
}
// NewLockRequest builds a policy service Lock endpoint payload.
func NewLockRequest(group string, policyName string, version string) *policy.LockRequest {
v := &policy.LockRequest{}
v.Group = group
v.PolicyName = policyName
v.Version = version
return v
}
// NewUnlockRequest builds a policy service Unlock endpoint payload.
func NewUnlockRequest(group string, policyName string, version string) *policy.UnlockRequest {
v := &policy.UnlockRequest{}
v.Group = group
v.PolicyName = policyName
v.Version = version
return v
}
// ValidateEvaluateRequestBody runs the validations defined on
// EvaluateRequestBody
func ValidateEvaluateRequestBody(body *EvaluateRequestBody) (err error) {
......
......@@ -16,12 +16,16 @@ import (
// Client is the "policy" service client.
type Client struct {
EvaluateEndpoint goa.Endpoint
LockEndpoint goa.Endpoint
UnlockEndpoint goa.Endpoint
}
// NewClient initializes a "policy" service client given the endpoints.
func NewClient(evaluate goa.Endpoint) *Client {
func NewClient(evaluate, lock, unlock goa.Endpoint) *Client {
return &Client{
EvaluateEndpoint: evaluate,
LockEndpoint: lock,
UnlockEndpoint: unlock,
}
}
......@@ -34,3 +38,15 @@ func (c *Client) Evaluate(ctx context.Context, p *EvaluateRequest) (res *Evaluat
}
return ires.(*EvaluateResult), nil
}
// Lock calls the "Lock" endpoint of the "policy" service.
func (c *Client) Lock(ctx context.Context, p *LockRequest) (err error) {
_, err = c.LockEndpoint(ctx, p)
return
}
// Unlock calls the "Unlock" endpoint of the "policy" service.
func (c *Client) Unlock(ctx context.Context, p *UnlockRequest) (err error) {
_, err = c.UnlockEndpoint(ctx, p)
return
}
......@@ -16,18 +16,24 @@ import (
// Endpoints wraps the "policy" service endpoints.
type Endpoints struct {
Evaluate goa.Endpoint
Lock goa.Endpoint
Unlock goa.Endpoint
}
// NewEndpoints wraps the methods of the "policy" service with endpoints.
func NewEndpoints(s Service) *Endpoints {
return &Endpoints{
Evaluate: NewEvaluateEndpoint(s),
Lock: NewLockEndpoint(s),
Unlock: NewUnlockEndpoint(s),
}
}
// Use applies the given middleware to all the "policy" service endpoints.
func (e *Endpoints) Use(m func(goa.Endpoint) goa.Endpoint) {
e.Evaluate = m(e.Evaluate)
e.Lock = m(e.Lock)
e.Unlock = m(e.Unlock)
}
// NewEvaluateEndpoint returns an endpoint function that calls the method
......@@ -38,3 +44,21 @@ func NewEvaluateEndpoint(s Service) goa.Endpoint {
return s.Evaluate(ctx, p)
}
}
// NewLockEndpoint returns an endpoint function that calls the method "Lock" of
// service "policy".
func NewLockEndpoint(s Service) goa.Endpoint {
return func(ctx context.Context, req interface{}) (interface{}, error) {
p := req.(*LockRequest)
return nil, s.Lock(ctx, p)
}
}
// NewUnlockEndpoint returns an endpoint function that calls the method
// "Unlock" of service "policy".
func NewUnlockEndpoint(s Service) goa.Endpoint {
return func(ctx context.Context, req interface{}) (interface{}, error) {
p := req.(*UnlockRequest)
return nil, s.Unlock(ctx, p)
}
}
......@@ -13,8 +13,12 @@ import (
// Policy Service provides evaluation of policies through Open Policy Agent.
type Service interface {
// Evaluate implements Evaluate.
// Evaluate executes a policy with the given 'data' as input.
Evaluate(context.Context, *EvaluateRequest) (res *EvaluateResult, err error)
// Lock a policy so that it cannot be evaluated.
Lock(context.Context, *LockRequest) (err error)
// Unlock a policy so it can be evaluated again.
Unlock(context.Context, *UnlockRequest) (err error)
}
// ServiceName is the name of the service as defined in the design. This is the
......@@ -25,7 +29,7 @@ const ServiceName = "policy"
// MethodNames lists the service method names as defined in the design. These
// are the same values that are set in the endpoint request contexts under the
// MethodKey key.
var MethodNames = [1]string{"Evaluate"}
var MethodNames = [3]string{"Evaluate", "Lock", "Unlock"}
// EvaluateRequest is the payload type of the policy service Evaluate method.
type EvaluateRequest struct {
......@@ -44,3 +48,23 @@ type EvaluateResult struct {
// Arbitrary JSON response.
Result interface{}
}
// LockRequest is the payload type of the policy service Lock method.
type LockRequest struct {
// Policy group
Group string
// Policy name
PolicyName string
// Policy version
Version string
}
// UnlockRequest is the payload type of the policy service Unlock method.
type UnlockRequest struct {
// Policy group
Group string
// Policy name
PolicyName string
// Policy version
Version string
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment