From 82a40d3efc2fe5d228ec50819e747e03398c0efc Mon Sep 17 00:00:00 2001 From: kchiranjewee63 Date: Wed, 29 May 2024 13:27:19 -0400 Subject: [PATCH] Add initial setup --- .github/workflows/service-lint.yml | 31 +++++ .gitignore | 21 ++++ LICENSE | 51 ++++++++ NOTICE | 13 ++ example-rules/order/verification-rules.ndjson | 43 +++++++ .../stocks/verification-rules.ndjson | 73 +++++++++++ example-rules/trats.ndjson | 115 ++++++++++++++++++ service/.gitignore | 21 ++++ service/.golangci.yml | 23 ++++ service/Dockerfile | 22 ++++ service/cmd/main.go | 74 +++++++++++ service/config.quick-start.yaml | 17 +++ service/go.mod | 13 ++ service/go.sum | 16 +++ service/handler/handler.go | 70 +++++++++++ service/pkg/apperrors/apperrors.go | 5 + service/pkg/rules/parse.go | 101 +++++++++++++++ service/pkg/rules/rules.go | 56 +++++++++ service/pkg/rules/types.go | 58 +++++++++ service/pkg/rules/validation.go | 86 +++++++++++++ service/pkg/service/service.go | 26 ++++ 21 files changed, 935 insertions(+) create mode 100644 .github/workflows/service-lint.yml create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 NOTICE create mode 100644 example-rules/order/verification-rules.ndjson create mode 100644 example-rules/stocks/verification-rules.ndjson create mode 100644 example-rules/trats.ndjson create mode 100644 service/.gitignore create mode 100644 service/.golangci.yml create mode 100644 service/Dockerfile create mode 100644 service/cmd/main.go create mode 100644 service/config.quick-start.yaml create mode 100644 service/go.mod create mode 100644 service/go.sum create mode 100644 service/handler/handler.go create mode 100644 service/pkg/apperrors/apperrors.go create mode 100644 service/pkg/rules/parse.go create mode 100644 service/pkg/rules/rules.go create mode 100644 service/pkg/rules/types.go create mode 100644 service/pkg/rules/validation.go create mode 100644 service/pkg/service/service.go diff --git a/.github/workflows/service-lint.yml b/.github/workflows/service-lint.yml new file mode 100644 index 0000000..b1f3fc6 --- /dev/null +++ b/.github/workflows/service-lint.yml @@ -0,0 +1,31 @@ +name: Lint tratD Service + +on: + push: + branches: [main] + paths: + - 'service/**' + pull_request: + branches: [main] + paths: + - 'service/**' + +jobs: + lint: + name: Run golangci-lint on tratD Service + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.22.0' + + - name: Install golangci-lint + uses: golangci/golangci-lint-action@v4 + with: + version: v1.54.2 + args: --timeout 5m --verbose + working-directory: ./service diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7cd1091 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# Go workspace file +go.work \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6ca24c7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,51 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..564237c --- /dev/null +++ b/NOTICE @@ -0,0 +1,13 @@ +Copyright 2024 SGNL.ai, INC. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/example-rules/order/verification-rules.ndjson b/example-rules/order/verification-rules.ndjson new file mode 100644 index 0000000..a4d06c1 --- /dev/null +++ b/example-rules/order/verification-rules.ndjson @@ -0,0 +1,43 @@ +{ + "type": "TraT-Verification-Rule", + "service": "order", + "route": "/order", + "method": "POST", + "rules": [ + { + "traT-name": "trade-trat", + "adz-mapping": { + "action": { + "path": "$body.action", + "required": true + }, + "quantity": { + "path": "$body.quantity", + "required": true + }, + "stock": { + "path": "$body.stockID", + "required": true + } + } + } + ] +} + +{ + "type": "TraT-Verification-Rule", + "service": "order", + "route": "/order/{id}", + "method": "GET", + "rules": [ + { + "traT-name": "trade-details-trat", + "adz-mapping": { + "id": { + "mappting": "${id}", + "required": true + } + } + } + ] +} \ No newline at end of file diff --git a/example-rules/stocks/verification-rules.ndjson b/example-rules/stocks/verification-rules.ndjson new file mode 100644 index 0000000..556f696 --- /dev/null +++ b/example-rules/stocks/verification-rules.ndjson @@ -0,0 +1,73 @@ +{ + "type": "TraT-Verification-Rule", + "service": "stocks", + "route": "/stocks/search", + "method": "GET", + "rules": [ + { + "traT-name": "stock-search-trat", + "adz-mapping": { + "query": { + "mapping": "$queryParameters.query", + "required": true + } + } + } + ] +} + +{ + "type": "TraT-Verification-Rule", + "service": "stocks", + "route": "/stocks/{id}", + "method": "GET", + "rules": [ + { + "traT-name": "stock-details-trat", + "adz-mapping": { + "stockID": { + "mapping": "${id}", + "required": true + } + } + } + ] +} + +{ + "type": "TraT-Verification-Rule", + "service": "stocks", + "route": "/stocks", + "method": "POST", + "rules": [ + { + "traT-name": "stock-update-trat", + "adz-mapping": { + "action": { + "path": "$body.action", + "required": true + }, + "quantity": { + "path": "$body.quantity", + "required": true + }, + "stock": { + "path": "$body.stockID", + "required": true + } + } + } + ] +} + +{ + "type": "TraT-Verification-Rule", + "service": "stocks", + "route": "/stocks/holdings", + "method": "GET", + "rules": [ + { + "traT-name": "portfolio-trat" + } + ] +} \ No newline at end of file diff --git a/example-rules/trats.ndjson b/example-rules/trats.ndjson new file mode 100644 index 0000000..8620205 --- /dev/null +++ b/example-rules/trats.ndjson @@ -0,0 +1,115 @@ +{ + "type": "TraT", + "traT-name": "stock-search-trat", + "scope": "stock-search", + "adz-schema": { + "query": {} + } +} + +{ + "type": "TraT-Generation-Rule", + "traT-name": "stock-search-trat", + "route": "/stocks/stock-search", + "method": "GET", + "adz-mapping": { + "query": "$queryParameters.query" + } +} + +{ + "type": "TraT", + "traT-name": "stock-details-trat", + "scope": "stock-details", + "adz-schema": { + "stockID": {} + } +} + +{ + "type": "TraT-Generation-Rule", + "traT-name": "stock-details-trat", + "route": "/stocks/{id}", + "method": "GET", + "adz-mapping": { + "stockID": "${id}" + } +} + +{ + "type": "TraT", + "traT-name": "stock-update-trat", + "scope": "stock-update", + "adz-schema": { + "action": {}, + "quantity": {}, + "stock": {} + } +} + +{ + "type": "TraT-Generation-Rule", + "route": "/stock", + "method": "POST", + "traT-name": "stock-update-trat", + "adz-mapping": { + "action": "$body.action", + "quantity": "$body.quantity", + "stock": "$body.stockID" + } +} + +{ + "type": "TraT", + "traT-name": "portfolio-trat", + "scope": "portfolio" +} + +{ + "type": "TraT-Generation-Rule", + "traT-name": "portfolio-trat", + "route": "/stocks/holdings", + "method": "GET" +} + +{ + "type": "TraT", + "traT-name": "trade-trat", + "scope": "trade", + "adz-schema": { + "action": {}, + "quantity": {}, + "stock": {} + } +} + +{ + "type": "TraT-Generation-Rule", + "traT-name": "trade-trat", + "route": "/order", + "method": "POST", + "adz-mapping": { + "action": "$body.action", + "quantity": "$body.quantity", + "stock": "$body.stockID" + } +} + +{ + "type": "TraT", + "traT-name": "trade-details-trat", + "scope": "trade-details", + "adz-schema": { + "id": {} + } +} + +{ + "type": "TraT-Generation-Rule", + "traT-name": "trade-details-trat", + "route": "/order/{id}", + "method": "GET", + "adz-mapping": { + "id": "${id}" + } +} \ No newline at end of file diff --git a/service/.gitignore b/service/.gitignore new file mode 100644 index 0000000..7cd1091 --- /dev/null +++ b/service/.gitignore @@ -0,0 +1,21 @@ +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# Go workspace file +go.work \ No newline at end of file diff --git a/service/.golangci.yml b/service/.golangci.yml new file mode 100644 index 0000000..d2696af --- /dev/null +++ b/service/.golangci.yml @@ -0,0 +1,23 @@ +linters: + disable-all: true + enable: + - asciicheck + - decorder + - dupword + - durationcheck + - forcetypeassert + - godot + - gofmt + - gosimple + - ineffassign + - makezero + - misspell + - nilerr + - nlreturn + - promlinter + - reassign + - unconvert + - unparam + - unused + - usestdlibvars + - wsl \ No newline at end of file diff --git a/service/Dockerfile b/service/Dockerfile new file mode 100644 index 0000000..fcc0a6e --- /dev/null +++ b/service/Dockerfile @@ -0,0 +1,22 @@ +# First stage: the build environment +FROM golang:1.22.0 as builder + +WORKDIR /app + +COPY go.mod go.sum ./ +RUN go mod download + +COPY . . + +RUN CGO_ENABLED=0 GOOS=linux go build -o tratD ./cmd + +# Second stage: the runtime environment +FROM alpine:latest + +RUN apk --no-cache add ca-certificates + +WORKDIR /app + +COPY --from=builder /app/tratD . + +ENTRYPOINT ["./tratD"] \ No newline at end of file diff --git a/service/cmd/main.go b/service/cmd/main.go new file mode 100644 index 0000000..9489ceb --- /dev/null +++ b/service/cmd/main.go @@ -0,0 +1,74 @@ +package main + +import ( + "log" + "net/http" + "os" + "time" + + "github.com/gorilla/mux" + "go.uber.org/zap" + + "github.com/tratteria/tratD/handler" + "github.com/tratteria/tratD/pkg/rules" + "github.com/tratteria/tratD/pkg/service" +) + +type App struct { + Router *mux.Router + Rules *rules.Rules + Logger *zap.Logger +} + +func main() { + logger, err := zap.NewProduction() + if err != nil { + log.Fatalf("Cannot initialize Zap logger: %v.", err) + } + + defer func() { + if err := logger.Sync(); err != nil { + log.Printf("Error syncing logger: %v", err) + } + }() + + if len(os.Args) < 2 { + logger.Error("Rules directory not provided. Please specify the rules directory as an argument when running the service.", + zap.String("usage", "tratD ")) + os.Exit(1) + } + + rulesDir := os.Args[1] + rules := rules.NewRules(rulesDir) + + err = rules.Load() + if err != nil { + logger.Fatal("Error loading rules:", zap.Error(err)) + } + + app := &App{ + Router: mux.NewRouter(), + Rules: rules, + Logger: logger, + } + + appService := service.NewService(app.Rules, app.Logger) + appHandler := handler.NewHandlers(appService, app.Logger) + + app.initializeRoutes(appHandler) + + srv := &http.Server{ + Handler: app.Router, + Addr: "0.0.0.0:9060", + WriteTimeout: 15 * time.Second, + ReadTimeout: 15 * time.Second, + } + + logger.Info("Starting server on 9060.") + log.Fatal(srv.ListenAndServe()) +} + +func (a *App) initializeRoutes(handlers *handler.Handlers) { + a.Router.HandleFunc("/verification-rules", handlers.GetVerificationRulesHandler).Methods("GET") + a.Router.HandleFunc("/generation-rules", handlers.GetGenerationRulesHandler).Methods("GET") +} diff --git a/service/config.quick-start.yaml b/service/config.quick-start.yaml new file mode 100644 index 0000000..2d174b6 --- /dev/null +++ b/service/config.quick-start.yaml @@ -0,0 +1,17 @@ +# Tratteria Quick-Start Configuration +# +# WARNING: This configuration is designed only for initial testing and evaluation. +# It omits important security and performance settings and SHOULD NOT be used in production environments. +# +# Please use config.example.yml as a reference for setting up a production-ready configuration. + + + +issuer: https://example.org/tts +audience: https://example.org/ +token: + lifeTime: "15s" +subjectTokens: + selfSigned: + validation: false +enableAccessEvaluation: false \ No newline at end of file diff --git a/service/go.mod b/service/go.mod new file mode 100644 index 0000000..35b179d --- /dev/null +++ b/service/go.mod @@ -0,0 +1,13 @@ +module github.com/tratteria/tratD + +go 1.22.0 + +require ( + github.com/gorilla/mux v1.8.1 + go.uber.org/zap v1.27.0 +) + +require ( + github.com/stretchr/testify v1.9.0 // indirect + go.uber.org/multierr v1.10.0 // indirect +) diff --git a/service/go.sum b/service/go.sum new file mode 100644 index 0000000..5b733f3 --- /dev/null +++ b/service/go.sum @@ -0,0 +1,16 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= +github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= +go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/service/handler/handler.go b/service/handler/handler.go new file mode 100644 index 0000000..508f694 --- /dev/null +++ b/service/handler/handler.go @@ -0,0 +1,70 @@ +package handler + +import ( + "encoding/json" + "errors" + "net/http" + + "github.com/tratteria/tratD/pkg/apperrors" + "github.com/tratteria/tratD/pkg/service" + + "go.uber.org/zap" +) + +type Handlers struct { + Service *service.Service + Logger *zap.Logger +} + +func NewHandlers(service *service.Service, logger *zap.Logger) *Handlers { + return &Handlers{ + Service: service, + Logger: logger, + } +} + +func (h *Handlers) GetVerificationRulesHandler(w http.ResponseWriter, r *http.Request) { + queryParams := r.URL.Query() + serviceName := queryParams.Get("service") + + if serviceName == "" { + http.Error(w, "Service parameter is required", http.StatusBadRequest) + return + } + + verificationRules, err := h.Service.GetVerificationRule(serviceName) + if err != nil { + if errors.Is(err, apperrors.ErrVerificationRuleNotFound) { + http.Error(w, err.Error(), http.StatusNotFound) + } else { + http.Error(w, "Internal Server error", http.StatusInternalServerError) + } + return + } + + response, err := json.Marshal(verificationRules) + if err != nil { + http.Error(w, "Failed to encode verification rules", http.StatusInternalServerError) + + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(response) +} + +func (h *Handlers) GetGenerationRulesHandler(w http.ResponseWriter, r *http.Request) { + generationRules := h.Service.GetGenerationRule() + + response, err := json.Marshal(generationRules) + if err != nil { + http.Error(w, "Failed to encode generation rules", http.StatusInternalServerError) + + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(response) +} diff --git a/service/pkg/apperrors/apperrors.go b/service/pkg/apperrors/apperrors.go new file mode 100644 index 0000000..e637f26 --- /dev/null +++ b/service/pkg/apperrors/apperrors.go @@ -0,0 +1,5 @@ +package apperrors + +import "errors" + +var ErrVerificationRuleNotFound = errors.New("verification rule not found for the service") \ No newline at end of file diff --git a/service/pkg/rules/parse.go b/service/pkg/rules/parse.go new file mode 100644 index 0000000..568b0cf --- /dev/null +++ b/service/pkg/rules/parse.go @@ -0,0 +1,101 @@ +package rules + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" +) + +func parse(dir string) (map[string]TraTDefinition, map[string]GenerationRule, map[string]map[string]VerificationRule, error) { + traTs := make(map[string]TraTDefinition) + generationRules := make(map[string]GenerationRule) + verificationRules := make(map[string]map[string]VerificationRule) + + err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if !info.IsDir() { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + reader := bufio.NewReader(file) + decoder := json.NewDecoder(reader) + + for { + var jsonData map[string]interface{} + if err := decoder.Decode(&jsonData); err == io.EOF { + break + } else if err != nil { + return err + } + + switch jsonType := jsonData["type"]; jsonType { + case "TraT": + var definition TraTDefinition + jsonBytes, err := json.Marshal(jsonData) + if err != nil { + return err + } + if err := json.Unmarshal(jsonBytes, &definition); err != nil { + return err + } + traTs[definition.TraTName] = definition + + case "TraT-Generation-Rule": + var genRule GenerationRule + jsonBytes, err := json.Marshal(jsonData) + if err != nil { + return err + } + if err := json.Unmarshal(jsonBytes, &genRule); err != nil { + return err + } + + key := genRule.Method + genRule.Route + if _, exists := generationRules[key]; exists { + return fmt.Errorf("multiple generation rules for route: %s, method: %s provided", genRule.Route, genRule.Method) + } + + generationRules[key] = genRule + + case "TraT-Verification-Rule": + var verRule VerificationRule + jsonBytes, err := json.Marshal(jsonData) + if err != nil { + return err + } + if err := json.Unmarshal(jsonBytes, &verRule); err != nil { + return err + } + + serviceVerificatinRules, exists := verificationRules[verRule.Service] + if !exists { + serviceVerificatinRules = make(map[string]VerificationRule) + verificationRules[verRule.Service] = serviceVerificatinRules + } + + key := verRule.Method + verRule.Route + if _, exists := serviceVerificatinRules[key]; exists { + return fmt.Errorf("multiple verification rules for service: %s, route: %s, method: %s provided", verRule.Service, verRule.Route, verRule.Method) + } + + serviceVerificatinRules[key] = verRule + } + } + } + return nil + }) + + if err != nil { + return nil, nil, nil, err + } + + return traTs, generationRules, verificationRules, nil +} diff --git a/service/pkg/rules/rules.go b/service/pkg/rules/rules.go new file mode 100644 index 0000000..3412acd --- /dev/null +++ b/service/pkg/rules/rules.go @@ -0,0 +1,56 @@ +package rules + +import ( + "github.com/tratteria/tratD/pkg/apperrors" +) + +type Rules struct { + dir string + traTs map[string]TraTDefinition + generationRules map[string]GenerationRule + verificationRules map[string]map[string]VerificationRule +} + +func NewRules(dir string) *Rules { + return &Rules{ + dir: dir, + traTs: make(map[string]TraTDefinition), + generationRules: make(map[string]GenerationRule), + verificationRules: make(map[string]map[string]VerificationRule), + } +} + +func (r *Rules) Load() error { + traTs, generationRules, verificationRules, err := parse(r.dir) + if err != nil { + return err + } + + if err := validateGenerationRules(generationRules, traTs); err != nil { + return err + } + + if err := validateVerificationRules(verificationRules, traTs); err != nil { + return err + } + + r.traTs = traTs + r.generationRules = generationRules + r.verificationRules = verificationRules + + return nil +} + +func (r *Rules) GetVerificationRules(service string) (map[string]VerificationRule, error) { + verificationRule, exist := r.verificationRules[service] + if !exist { + return nil, apperrors.ErrVerificationRuleNotFound + } + + return verificationRule, nil +} + +func (r *Rules) GetGenerationRules() map[string]GenerationRule { + + return r.generationRules +} diff --git a/service/pkg/rules/types.go b/service/pkg/rules/types.go new file mode 100644 index 0000000..a470488 --- /dev/null +++ b/service/pkg/rules/types.go @@ -0,0 +1,58 @@ +package rules + +import ( + "encoding/json" + "fmt" +) + +type TraTDefinition struct { + Type string `json:"type"` + TraTName string `json:"traT-name"` + Scope string `json:"scope"` + AdzSchema map[string]interface{} `json:"adz-schema"` +} + +type GenerationRule struct { + Type string `json:"type"` + Route string `json:"route"` + Method string `json:"method"` + TraTName string `json:"traT-name"` + AdzMapping map[string]interface{} `json:"adz-mapping"` +} + +type VerificationRule struct { + Type string `json:"type"` + Service string `json:"service"` + Route string `json:"route"` + Method string `json:"method"` + Rules []Rule `json:"rules"` +} + +type Rule struct { + TraTName string `json:"traT-name"` + AdzMapping map[string]VerificationAdzField `json:"adz-mapping"` +} + +type VerificationAdzField struct { + Path string `json:"path"` + Required bool `json:"required"` +} + +func (v *VerificationAdzField) UnmarshalJSON(data []byte) error { + var obj struct { + Path string `json:"path"` + Required bool `json:"required"` + } + if err := json.Unmarshal(data, &obj); err == nil { + *v = VerificationAdzField{Path: obj.Path, Required: obj.Required} + return nil + } + + var path string + if err := json.Unmarshal(data, &path); err == nil { + *v = VerificationAdzField{Path: path, Required: false} + return nil + } + + return fmt.Errorf("cannot unmarshal verification rule adz-mapping VerificationAdzField: %s", data) +} diff --git a/service/pkg/rules/validation.go b/service/pkg/rules/validation.go new file mode 100644 index 0000000..d334f3f --- /dev/null +++ b/service/pkg/rules/validation.go @@ -0,0 +1,86 @@ +package rules + +import ( + "fmt" +) + +// TODO +// 1. Add validation if JSON paths are valid and referencing valid variables i.e body, header, or queryParameters +// 2. Add validation if referenced url-path parameters are correct +// 3. Add validation if route is correct i.e begins with leading slash + +var validMethods = map[string]struct{}{ + "GET": {}, + "POST": {}, + "PUT": {}, + "DELETE": {}, + "PATCH": {}, + "OPTIONS": {}, + "HEAD": {}, +} + +func isValidHTTPMethod(method string) bool { + _, exists := validMethods[method] + return exists +} + +func validateGenerationRules(genRules map[string]GenerationRule, traTs map[string]TraTDefinition) error { + for _, genRule := range genRules { + traT, exist := traTs[genRule.TraTName] + if !exist { + return fmt.Errorf("invalid TraT %s referenced in TraT generation rule for route: %s, method: %s", genRule.TraTName, genRule.Route, genRule.Method) + } + + if !isValidHTTPMethod(genRule.Method) { + return fmt.Errorf("invalid HTTP method %s in generation rule for route: %s", genRule.Method, genRule.Route) + } + + if err := validateAdzMapping(genRule.AdzMapping, traT); err != nil { + return fmt.Errorf("invalid adz mapping in TraT generation rule; traT: %s, route: %s, method: %s; error: %s", genRule.TraTName, genRule.Route, genRule.Method, err.Error()) + } + } + return nil +} + +func validateVerificationRules(verRules map[string]map[string]VerificationRule, traTs map[string]TraTDefinition) error { + for _, serviceVerRules := range verRules { + for _, verRule := range serviceVerRules { + if !isValidHTTPMethod(verRule.Method) { + return fmt.Errorf("invalid HTTP method %s in verification rule for route: %s", verRule.Method, verRule.Route) + } + + for _, rule := range verRule.Rules { + traT, exist := traTs[rule.TraTName] + if !exist { + return fmt.Errorf("invalid TraT %s referenced in TraT verification rule for route: %s, method: %s", rule.TraTName, verRule.Route, verRule.Method) + } + + if err := validateAdzMapping(rule.AdzMapping, traT); err != nil { + return fmt.Errorf("invalid adz mapping in TraT verification rule; traT: %s, route: %s, method: %s; error: %s", rule.TraTName, verRule.Route, verRule.Method, err.Error()) + } + } + } + } + return nil +} + +func validateAdzMapping(adzMapping interface{}, traT TraTDefinition) error { + switch v := adzMapping.(type) { + case map[string]interface{}: + for field := range v { + if _, ok := traT.AdzSchema[field]; !ok { + return fmt.Errorf("invalid key '%s' in generation rule adz mapping", field) + } + } + case map[string]VerificationAdzField: + for field := range v { + if _, ok := traT.AdzSchema[field]; !ok { + return fmt.Errorf("invalid key '%s' in verification rule adz mapping", field) + } + } + default: + return fmt.Errorf("unknown type for adz mapping") + } + + return nil +} diff --git a/service/pkg/service/service.go b/service/pkg/service/service.go new file mode 100644 index 0000000..8008059 --- /dev/null +++ b/service/pkg/service/service.go @@ -0,0 +1,26 @@ +package service + +import ( + "github.com/tratteria/tratD/pkg/rules" + "go.uber.org/zap" +) + +type Service struct { + Rules *rules.Rules + Logger *zap.Logger +} + +func NewService(rules *rules.Rules, logger *zap.Logger) *Service { + return &Service{ + Rules: rules, + Logger: logger, + } +} + +func (s *Service) GetVerificationRule(service string) (map[string]rules.VerificationRule, error) { + return s.Rules.GetVerificationRules(service) +} + +func (s *Service) GetGenerationRule() map[string]rules.GenerationRule { + return s.Rules.GetGenerationRules() +}