diff --git a/.github/templates/README.template.md b/.github/templates/README.template.md index 2763833..71b38ec 100644 --- a/.github/templates/README.template.md +++ b/.github/templates/README.template.md @@ -80,10 +80,10 @@ Notice the `@` infront of `authorization`. See [KeyValue Pair Injection](#keyval ### Example -To send a message to 1234567: +To send a message to `+123400002`: ```bash -curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer API_TOKEN" -d '{"message": "Hello World!", "recipients": ["1234567"]}' http://sec-signal-api:8880/v2/send +curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer API_TOKEN" -d '{"message": "Hello World!", "recipients": ["+123400002"]}' http://sec-signal-api:8880/v2/send ``` ### Advanced @@ -160,10 +160,10 @@ Suppose you want to set a new [Placeholder](#placeholders) `NUMBER` in your Envi ```yaml environment: - VARIABLES__NUMBER: "000" + SETTINGS__VARIABLES__NUMBER: "+123400001" ``` -This would internally be converted into `variables.number` matching the config formatting. +This would internally be converted into `settings.variables.number` matching the config formatting. > [!IMPORTANT] > Underscores `_` are removed during Conversion, Double Underscores `__` on the other hand convert the Variable into a nested Object (`__` replaced by `.`) @@ -200,41 +200,41 @@ api: ``` > [!IMPORTANT] -> It is highly recommended use API Tokens - -> _What if I just don't?_ - -Secured Signal API will still work, but important Security Features won't be available -like Blocked Endpoints and any sort of Auth. +> Using API Tokens is highly recommended, but not mandatory. +> Some important Security Features won't be available (like default Blocked Endpoints). > [!NOTE] > Blocked Endpoints can be reactivated by manually configuring them ### Endpoints -Because Secured Signal API is just a Proxy you can use all of the [Signal REST API](https://github.com/bbernhard/signal-cli-rest-api/blob/master/doc/EXAMPLES.md) endpoints except for... +Since Secured Signal API is just a Proxy you can use all of the [Signal REST API](https://github.com/bbernhard/signal-cli-rest-api/blob/master/doc/EXAMPLES.md) endpoints except for... + +| Endpoint | | +| :-------------------- | ------------------ | +| **/v1/about** | **/v1/unregister** | +| **/v1/configuration** | **/v1/qrcodelink** | +| **/v1/devives** | **/v1/contacts** | +| **/v1/register** | **/v1/accounts** | -| Endpoint | -| :-------------------- | -| **/v1/about** | -| **/v1/configuration** | -| **/v1/devives** | -| **/v1/register** | -| **/v1/unregister** | -| **/v1/qrcodelink** | -| **/v1/accounts** | -| **/v1/contacts** | +These Endpoints are blocked by default due to Security Risks. > [!NOTE] -> Matching works by checking if the requested Endpoints startswith a Blocked or Allowed Endpoint +> Matching works by checking if the requested Endpoints starts with a Blocked or an Allowed Endpoint -These Endpoints are blocked by default due to Security Risks, but can be modified by setting `blockedEndpoints` in your config: +You can modify Blocked Endpoints by configuring `blockedEndpoints` in your config: ```yaml -blockedEndpoints: [/v1/register, /v1/unregister, /v1/qrcodelink, /v1/contacts] +settings: + blockedEndpoints: [/v1/register, /v1/unregister, /v1/qrcodelink, /v1/contacts] ``` -Override Blocked Endpoints by explicitly allowing endpoints in `allowedEndpoints`. +You can also override Blocked Endpoints by adding Allowed Endpoints to `allowedEndpoints`. + +```yaml +settings: + allowedEndpoints: [/v2/send] +``` | Config (Allow) | (Block) | Result | | | | | :------------------------------- | :---------------------------------- | :--------: | --- | :---------------: | --- | @@ -242,10 +242,6 @@ Override Blocked Endpoints by explicitly allowing endpoints in `allowedEndpoints | `unset` | `blockedEndpoints: ["/v1/receive"]` | **all** | ✅ | **`/v1/receive`** | 🛑 | | `blockedEndpoints: ["/v2"]` | `allowedEndpoints: ["/v2/send"]` | **`/v2*`** | 🛑 | **`/v2/send`** | ✅ | -```yaml -allowedEndpoints: [/v2/send] -``` - ### Variables Placeholders can be added under `variables` and can then be referenced in the Body, Query or URL. @@ -256,40 +252,38 @@ See [Placeholders](#placeholders). > Example: `number` becomes `NUMBER` in `{{.NUMBER}}` ```yaml -variables: - number: "001", - recipients: [ - "user.id", "000", "001", "group.id" - ] +settings: + variables: + number: "+123400001", + recipients: ["+123400002", "group.id", "user.id"] ``` ### Message Aliases To improve compatibility with other services Secured Signal API provides aliases for the `message` attribute by default: -| Alias | Score | -| ----------- | ----- | -| msg | 100 | -| content | 99 | -| description | 98 | -| text | 20 | -| body | 15 | -| summary | 10 | -| details | 9 | -| payload | 2 | -| data | 1 | +| Alias | Score | Alias | Score | +| ------------ | ----- | ---------------- | ----- | +| msg | 100 | data.content | 9 | +| content | 99 | data.description | 8 | +| description | 98 | data.text | 7 | +| text | 20 | data.summary | 6 | +| summary | 15 | data.details | 5 | +| details | 14 | body | 2 | +| data.message | 10 | data | 1 | Secured Signal API will pick the best scoring Message Alias (if available) to extract the correct message from the Request Body. Message Aliases can be added by setting `messageAliases` in your config: ```yaml -messageAliases: - [ - { alias: "msg", score: 80 }, - { alias: "data.message", score: 79 }, - { alias: "array[0].message", score: 78 }, - ] +settings: + messageAliases: + [ + { alias: "msg", score: 80 }, + { alias: "data.message", score: 79 }, + { alias: "array[0].message", score: 78 }, + ] ``` ### Port diff --git a/config/defaults.yml b/config/defaults.yml index db61d52..5b2a0fa 100644 --- a/config/defaults.yml +++ b/config/defaults.yml @@ -1,39 +1,39 @@ server: port: 8880 -logLevel: INFO +logLevel: info -messageAliases: - [ - { alias: msg, score: 100 }, - { alias: content, score: 99 }, - { alias: description, score: 98 }, - { alias: text, score: 20 }, - { alias: summary, score: 15 }, - { alias: details, score: 14 }, +settings: + messageAliases: + [ + { alias: msg, score: 100 }, + { alias: content, score: 99 }, + { alias: description, score: 98 }, + { alias: text, score: 20 }, + { alias: summary, score: 15 }, + { alias: details, score: 14 }, - { alias: data.message, score: 10 }, - { alias: data.content, score: 9 }, - { alias: data.description, score: 8 }, - { alias: data.text, score: 7 }, - { alias: data.summary, score: 6 }, - { alias: data.details, score: 5 }, + { alias: data.message, score: 10 }, + { alias: data.content, score: 9 }, + { alias: data.description, score: 8 }, + { alias: data.text, score: 7 }, + { alias: data.summary, score: 6 }, + { alias: data.details, score: 5 }, - { alias: payload, score: 3 }, - { alias: body, score: 2 }, - { alias: data, score: 1 }, - ] + { alias: body, score: 2 }, + { alias: data, score: 1 }, + ] -variables: - recipients: ${RECIPIENTS} - number: ${NUMBER} + variables: + recipients: ${RECIPIENTS} + number: ${NUMBER} -blockedEndpoints: - - /v1/about - - /v1/configuration - - /v1/devices - - /v1/register - - /v1/unregister - - /v1/qrcodelink - - /v1/accounts - - /v1/contacts + blockedEndpoints: + - /v1/about + - /v1/configuration + - /v1/devices + - /v1/register + - /v1/unregister + - /v1/qrcodelink + - /v1/accounts + - /v1/contacts diff --git a/docker-compose.yaml b/docker-compose.yaml index 92e5c08..e5addac 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -6,27 +6,28 @@ services: - MODE=normal volumes: - ./data:/home/.local/share/signal-cli + restart: unless-stopped networks: backend: aliases: - signal-api - restart: unless-stopped secured-signal: image: ghcr.io/codeshelldev/secured-signal-api:latest container_name: secured-signal - networks: - backend: - aliases: - - secured-signal-api environment: API__URL: http://signal-api:8080 - VARIABLES__RECIPIENTS: '[000,001,002]' - VARIABLES__NUMBER: 123456789 - API__TOKENS: '[LOOOOOONG_STRING]' + SETTINGS__VARIABLES__RECIPIENTS: + ["+123400002", "+123400003", "+123400004"] + SETTINGS__VARIABLES__NUMBER: "+123400001" + API__TOKENS: [LOOOOOONG_STRING] ports: - "8880:8880" restart: unless-stopped + networks: + backend: + aliases: + - secured-signal-api networks: backend: diff --git a/examples/config.yml b/examples/config.yml index 2e5bb2c..9be5a31 100644 --- a/examples/config.yml +++ b/examples/config.yml @@ -7,13 +7,14 @@ api: logLevel: INFO -variables: - number: "000" - recipients: ["001", "group.id", "user.id"] +settings: + variables: + number: "+123400001" + recipients: ["+123400002", "group.id", "user.id"] -messageAliases: [{ alias: "msg", score: 100 }] + messageAliases: [{ alias: "msg", score: 100 }] -blockedEndpoints: - - /v1/about -allowedEndpoints: - - /v2/send + blockedEndpoints: + - /v1/about + allowedEndpoints: + - /v2/send diff --git a/examples/traefik.docker-compose.yaml b/examples/traefik.docker-compose.yaml index c2ec70a..c64819a 100644 --- a/examples/traefik.docker-compose.yaml +++ b/examples/traefik.docker-compose.yaml @@ -2,16 +2,11 @@ services: secured-signal: image: ghcr.io/codeshelldev/secured-signal-api:latest container_name: secured-signal - networks: - proxy: - backend: - aliases: - - secured-signal-api environment: API__URL: http://signal-api:8080 - VARIABLES__RECIPIENTS: '[000,001,002]' - VARIABLES__NUMBER: 123456789 - API__TOKENS: '[LOOOOOONG_STRING]' + SETTINGS__VARIABLES__RECIPIENTS: ["123400002", "123400003", "123400004"] + SETTINGS__VARIABLES__NUMBER: "+123400001" + API__TOKENS: [LOOOOOONG_STRING] labels: - traefik.enable=true - traefik.http.routers.signal-api.rule=Host(`signal-api.mydomain.com`) @@ -22,6 +17,11 @@ services: - traefik.http.services.signal-api-svc.loadbalancer.server.port=8880 - traefik.docker.network=proxy restart: unless-stopped + networks: + proxy: + backend: + aliases: + - secured-signal-api networks: backend: diff --git a/go.mod b/go.mod index fc1c638..2a1dfdd 100644 --- a/go.mod +++ b/go.mod @@ -2,20 +2,17 @@ module github.com/codeshelldev/secured-signal-api go 1.25.1 -require ( - go.uber.org/zap v1.27.0 - gopkg.in/yaml.v3 v3.0.1 -) +require go.uber.org/zap v1.27.0 require ( github.com/fsnotify/fsnotify v1.9.0 // indirect - github.com/go-viper/mapstructure/v2 v2.3.0 // indirect + github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/knadh/koanf/maps v0.1.2 // indirect github.com/knadh/koanf/parsers/yaml v1.1.0 github.com/knadh/koanf/providers/confmap v1.0.0 github.com/knadh/koanf/providers/env/v2 v2.0.0 github.com/knadh/koanf/providers/file v1.2.0 - github.com/knadh/koanf/v2 v2.2.2 + github.com/knadh/koanf/v2 v2.3.0 github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect go.uber.org/multierr v1.11.0 // indirect diff --git a/go.sum b/go.sum index 166ba14..cd5ee27 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,8 @@ 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/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= -github.com/go-viper/mapstructure/v2 v2.3.0 h1:27XbWsHIqhbdR5TIC911OfYvgSaW93HM+dX7970Q7jk= -github.com/go-viper/mapstructure/v2 v2.3.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo= github.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI= github.com/knadh/koanf/parsers/yaml v1.1.0 h1:3ltfm9ljprAHt4jxgeYLlFPmUaunuCgu1yILuTXRdM4= @@ -14,8 +14,8 @@ github.com/knadh/koanf/providers/env/v2 v2.0.0 h1:Ad5H3eun722u+FvchiIcEIJZsZ2M6o github.com/knadh/koanf/providers/env/v2 v2.0.0/go.mod h1:1g01PE+Ve1gBfWNNw2wmULRP0tc8RJrjn5p2N/jNCIc= github.com/knadh/koanf/providers/file v1.2.0 h1:hrUJ6Y9YOA49aNu/RSYzOTFlqzXSCpmYIDXI7OJU6+U= github.com/knadh/koanf/providers/file v1.2.0/go.mod h1:bp1PM5f83Q+TOUu10J/0ApLBd9uIzg+n9UgthfY+nRA= -github.com/knadh/koanf/v2 v2.2.2 h1:ghbduIkpFui3L587wavneC9e3WIliCgiCgdxYO/wd7A= -github.com/knadh/koanf/v2 v2.2.2/go.mod h1:abWQc0cBXLSF/PSOMCB/SK+T13NXDsPvOksbpi5e/9Q= +github.com/knadh/koanf/v2 v2.3.0 h1:Qg076dDRFHvqnKG97ZEsi9TAg2/nFTa9hCdcSa1lvlM= +github.com/knadh/koanf/v2 v2.3.0/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= diff --git a/internals/proxy/middlewares/body.go b/internals/proxy/middlewares/body.go index 67619d8..25f01fe 100644 --- a/internals/proxy/middlewares/body.go +++ b/internals/proxy/middlewares/body.go @@ -7,7 +7,7 @@ import ( "strconv" middlewareTypes "github.com/codeshelldev/secured-signal-api/internals/proxy/middlewares/types" - "github.com/codeshelldev/secured-signal-api/utils" + jsonutils "github.com/codeshelldev/secured-signal-api/utils/jsonutils" log "github.com/codeshelldev/secured-signal-api/utils/logger" request "github.com/codeshelldev/secured-signal-api/utils/request" ) @@ -90,7 +90,7 @@ func getMessage(aliases []middlewareTypes.MessageAlias, data map[string]any) (st func processAlias(alias middlewareTypes.MessageAlias, data map[string]any) (string, int, bool) { aliasKey := alias.Alias - value, ok := utils.GetByPath(aliasKey, data) + value, ok := jsonutils.GetByPath(aliasKey, data) aliasValue, isStr := value.(string) diff --git a/internals/proxy/middlewares/template.go b/internals/proxy/middlewares/template.go index 83d5a3a..25946ba 100644 --- a/internals/proxy/middlewares/template.go +++ b/internals/proxy/middlewares/template.go @@ -7,11 +7,11 @@ import ( "net/url" "strconv" - "github.com/codeshelldev/secured-signal-api/utils" + jsonutils "github.com/codeshelldev/secured-signal-api/utils/jsonutils" log "github.com/codeshelldev/secured-signal-api/utils/logger" - "github.com/codeshelldev/secured-signal-api/utils/query" + query "github.com/codeshelldev/secured-signal-api/utils/query" request "github.com/codeshelldev/secured-signal-api/utils/request" - "github.com/codeshelldev/secured-signal-api/utils/templating" + templating "github.com/codeshelldev/secured-signal-api/utils/templating" ) type TemplateMiddleware struct { @@ -113,8 +113,8 @@ func TemplateBody(data map[string]any, VARIABLES any) (map[string]any, bool, err return data, false, err } - beforeStr := utils.ToJson(templatedData) - afterStr := utils.ToJson(data) + beforeStr := jsonutils.ToJson(templatedData) + afterStr := jsonutils.ToJson(data) modified = beforeStr == afterStr diff --git a/main.go b/main.go index 9a8cdb5..da4c76a 100644 --- a/main.go +++ b/main.go @@ -25,10 +25,12 @@ func main() { ENV = config.ENV - if ENV.LOG_LEVEL != "" { + if ENV.LOG_LEVEL != log.Level() { log.Init(ENV.LOG_LEVEL) } + log.Info("Initialized Logger with Level of ", log.Level()) + initHandler = proxy.Create(ENV.API_URL) body_m4 := middlewares.BodyMiddleware{ diff --git a/tests/json_test.go b/tests/json_test.go index 1e92182..399ba48 100644 --- a/tests/json_test.go +++ b/tests/json_test.go @@ -3,8 +3,8 @@ package tests import ( "testing" - "github.com/codeshelldev/secured-signal-api/utils" - "github.com/codeshelldev/secured-signal-api/utils/templating" + jsonutils "github.com/codeshelldev/secured-signal-api/utils/jsonutils" + templating "github.com/codeshelldev/secured-signal-api/utils/templating" ) func TestJsonTemplating(t *testing.T) { @@ -28,7 +28,7 @@ func TestJsonTemplating(t *testing.T) { "key2": "{{.int}}" }` - data := utils.GetJson[map[string]any](json) + data := jsonutils.GetJson[map[string]any](json) expected := map[string]any{ "dict": map[string]any{ @@ -48,8 +48,8 @@ func TestJsonTemplating(t *testing.T) { t.Error("Error Templating JSON: ", err.Error()) } - expectedStr := utils.ToJson(expected) - gotStr := utils.ToJson(got) + expectedStr := jsonutils.ToJson(expected) + gotStr := jsonutils.ToJson(got) if expectedStr != gotStr { t.Error("\nExpected: ", expectedStr, "\nGot: ", gotStr) @@ -71,7 +71,7 @@ func TestJsonPath(t *testing.T) { "key": "val" }` - data := utils.GetJson[map[string]any](json) + data := jsonutils.GetJson[map[string]any](json) cases := []struct{ key string @@ -107,7 +107,7 @@ func TestJsonPath(t *testing.T) { key := c.key expected := c.expected - got, ok := utils.GetByPath(key, data) + got, ok := jsonutils.GetByPath(key, data) if !ok || got.(string) != expected { t.Error("Expected: ", key, " == ", expected, "; Got: ", got) diff --git a/tests/request_test.go b/tests/request_test.go index bfa016e..d1bf6f7 100644 --- a/tests/request_test.go +++ b/tests/request_test.go @@ -3,9 +3,9 @@ package tests import ( "testing" - "github.com/codeshelldev/secured-signal-api/utils" - "github.com/codeshelldev/secured-signal-api/utils/query" - "github.com/codeshelldev/secured-signal-api/utils/templating" + jsonutils "github.com/codeshelldev/secured-signal-api/utils/jsonutils" + query "github.com/codeshelldev/secured-signal-api/utils/query" + templating "github.com/codeshelldev/secured-signal-api/utils/templating" ) func TestQueryTemplating(t *testing.T) { @@ -45,8 +45,8 @@ func TestTypedQuery(t *testing.T) { }, } - expectedStr := utils.ToJson(expected) - gotStr := utils.ToJson(got) + expectedStr := jsonutils.ToJson(expected) + gotStr := jsonutils.ToJson(got) if expectedStr != gotStr { t.Error("\nExpected: ", expectedStr, "\nGot: ", gotStr) diff --git a/tests/string_test.go b/tests/string_test.go index e7d79b0..8b2186a 100644 --- a/tests/string_test.go +++ b/tests/string_test.go @@ -4,13 +4,13 @@ import ( "reflect" "testing" - "github.com/codeshelldev/secured-signal-api/utils/safestrings" + stringutils "github.com/codeshelldev/secured-signal-api/utils/stringutils" ) func TestStringEscaping(t *testing.T) { str1 := `\#` - res1 := safestrings.IsEscaped(str1, "#") + res1 := stringutils.IsEscaped(str1, "#") if !res1 { t.Error("Expected: ", str1, " == true", "; Got: ", str1, " == ", res1) @@ -18,7 +18,7 @@ func TestStringEscaping(t *testing.T) { str2 := "#" - res2 := safestrings.IsEscaped(str2, "#") + res2 := stringutils.IsEscaped(str2, "#") if res2 { t.Error("Expected: ", str2, " == false", "; Got: ", str2, " == ", res2) @@ -26,7 +26,7 @@ func TestStringEscaping(t *testing.T) { str3 := `#\#` - res3 := safestrings.Contains(str3, "#") + res3 := stringutils.Contains(str3, "#") if !res3 { t.Error("Expected: ", str3, " == true", "; Got: ", str3, " == ", res3) @@ -36,7 +36,7 @@ func TestStringEscaping(t *testing.T) { func TestStringEnclosement(t *testing.T) { str1 := "[enclosed]" - res1 := safestrings.IsEnclosedBy(str1, `[`, `]`) + res1 := stringutils.IsEnclosedBy(str1, `[`, `]`) if !res1 { t.Error("Expected: ", str1, " == true", "; Got: ", str1, " == ", res1) @@ -44,7 +44,7 @@ func TestStringEnclosement(t *testing.T) { str2 := `\[enclosed]` - res2 := safestrings.IsEnclosedBy(str2, `[`, `]`) + res2 := stringutils.IsEnclosedBy(str2, `[`, `]`) if res2 { t.Error("Expected: ", str2, " == false", "; Got: ", str2, " == ", res2) @@ -54,7 +54,7 @@ func TestStringEnclosement(t *testing.T) { func TestStringToType(t *testing.T) { str1 := `[item1,item2]` - res1 := safestrings.ToType(str1) + res1 := stringutils.ToType(str1) if reflect.TypeOf(res1) != reflect.TypeFor[[]string]() { t.Error("Expected: ", str1, " == []string", "; Got: ", str1, " == ", reflect.TypeOf(res1)) @@ -62,7 +62,7 @@ func TestStringToType(t *testing.T) { str2 := `1` - res2 := safestrings.ToType(str2) + res2 := stringutils.ToType(str2) if reflect.TypeOf(res2) != reflect.TypeFor[int]() { t.Error("Expected: ", str2, " == int", "; Got: ", str2, " == ", reflect.TypeOf(res2)) @@ -70,7 +70,7 @@ func TestStringToType(t *testing.T) { str3 := `{ "key": "value" }` - res3 := safestrings.ToType(str3) + res3 := stringutils.ToType(str3) if reflect.TypeOf(res3) != reflect.TypeFor[map[string]any]() { t.Error("Expected: ", str3, " == map[string]any", "; Got: ", str3, " == ", reflect.TypeOf(res3)) diff --git a/utils/config/config.go b/utils/config/config.go index 8b0ed54..46ff6a5 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -8,7 +8,7 @@ import ( "sync" log "github.com/codeshelldev/secured-signal-api/utils/logger" - "github.com/codeshelldev/secured-signal-api/utils/safestrings" + stringutils "github.com/codeshelldev/secured-signal-api/utils/stringutils" "github.com/knadh/koanf/providers/confmap" "github.com/knadh/koanf/providers/env/v2" @@ -25,6 +25,8 @@ var config *koanf.Koanf var configLock sync.Mutex func LoadFile(path string, config *koanf.Koanf, parser koanf.Parser) (koanf.Provider, error) { + log.Debug("Loading Config File: ", path) + f := file.Provider(path) err := config.Load(f, parser) @@ -216,5 +218,5 @@ func normalizeEnv(key string, value string) (string, any) { key = strings.ReplaceAll(key, "__", ".") key = strings.ReplaceAll(key, "_", "") - return key, safestrings.ToType(value) + return key, stringutils.ToType(value) } \ No newline at end of file diff --git a/utils/config/loader.go b/utils/config/loader.go index 598f806..0258b6d 100644 --- a/utils/config/loader.go +++ b/utils/config/loader.go @@ -8,8 +8,9 @@ import ( "strings" middlewareTypes "github.com/codeshelldev/secured-signal-api/internals/proxy/middlewares/types" - "github.com/codeshelldev/secured-signal-api/utils" + jsonutils "github.com/codeshelldev/secured-signal-api/utils/jsonutils" log "github.com/codeshelldev/secured-signal-api/utils/logger" + "github.com/knadh/koanf/parsers/yaml" ) @@ -38,37 +39,11 @@ var ENV *ENV_ = &ENV_{ TOKENS_DIR: os.Getenv("TOKENS_DIR"), API_TOKENS: []string{}, SETTINGS: map[string]*SETTING_{ - "*": { - BLOCKED_ENDPOINTS: []string{}, - ALLOWED_ENDPOINTS: []string{}, - MESSAGE_ALIASES: []middlewareTypes.MessageAlias{}, - VARIABLES: map[string]any{}, - }, + }, INSECURE: false, } -func InitEnv() { - ENV.PORT = strconv.Itoa(config.Int("server.port")) - - ENV.LOG_LEVEL = config.String("loglevel") - - ENV.API_URL = config.String("api.url") - - defaultSettings := ENV.SETTINGS["*"] - - config.Unmarshal("messagealiases", &defaultSettings.MESSAGE_ALIASES) - - transformChildren(config, "variables", func(key string, value any) (string, any) { - return strings.ToUpper(key), value - }) - - config.Unmarshal("variables", &defaultSettings.VARIABLES) - - defaultSettings.BLOCKED_ENDPOINTS = config.Strings("blockedendpoints") - defaultSettings.ALLOWED_ENDPOINTS = config.Strings("allowedendpoints") -} - func Load() { LoadDefaults() @@ -76,14 +51,11 @@ func Load() { LoadTokens() - log.Debug("Loading DotEnv") - LoadEnv(userLayer) config = mergeLayers() normalizeKeys(config) - templateConfig(config) InitTokens() @@ -92,13 +64,31 @@ func Load() { log.Info("Finished Loading Configuration") - log.Dev("Loaded Config:\n" + utils.ToJson(config.All())) - log.Dev("Loaded Token Configs:\n" + utils.ToJson(tokensLayer.All())) + log.Dev("Loaded Config:\n" + jsonutils.ToJson(config.All())) + log.Dev("Loaded Token Configs:\n" + jsonutils.ToJson(tokensLayer.All())) } -func LoadDefaults() { - log.Debug("Loading Config ", ENV.DEFAULTS_PATH) +func InitEnv() { + ENV.PORT = strconv.Itoa(config.Int("server.port")) + ENV.LOG_LEVEL = strings.ToLower(config.String("loglevel")) + + ENV.API_URL = config.String("api.url") + + var settings SETTING_ + + transformChildren(config, "settings.variables", func(key string, value any) (string, any) { + return strings.ToUpper(key), value + }) + + config.Unmarshal("settings", &settings) + + log.Dev(jsonutils.ToJson(settings)) + + ENV.SETTINGS["*"] = &settings +} + +func LoadDefaults() { _, defErr := LoadFile(ENV.DEFAULTS_PATH, defaultsLayer, yaml.Parser()) if defErr != nil { @@ -107,8 +97,6 @@ func LoadDefaults() { } func LoadConfig() { - log.Debug("Loading Config ", ENV.CONFIG_PATH) - _, conErr := LoadFile(ENV.CONFIG_PATH, userLayer, yaml.Parser()) if conErr != nil { diff --git a/utils/utils.go b/utils/jsonutils/jsonutils.go similarity index 71% rename from utils/utils.go rename to utils/jsonutils/jsonutils.go index 2159e1b..2365c08 100644 --- a/utils/utils.go +++ b/utils/jsonutils/jsonutils.go @@ -1,16 +1,9 @@ -package utils - -/* - * General Functions (utils) - * Might move Functions into seperate files - */ +package jsonutils import ( "encoding/json" "regexp" "strconv" - - "gopkg.in/yaml.v3" ) func GetByPath(path string, data any) (any, bool) { @@ -67,31 +60,7 @@ func GetJsonSafe[T any](jsonStr string) (T, error) { func GetJson[T any](jsonStr string) (T) { var result T - err := json.Unmarshal([]byte(jsonStr), &result) - - if err != nil { - // YML is empty - } - - return result -} - -func GetYmlSafe[T any](ymlStr string) (T, error) { - var result T - - err := yaml.Unmarshal([]byte(ymlStr), &result) - - return result, err -} - -func GetYml[T any](ymlStr string) (T) { - var result T - - err := yaml.Unmarshal([]byte(ymlStr), &result) - - if err != nil { - // YML is empty - } + json.Unmarshal([]byte(jsonStr), &result) return result } @@ -103,11 +72,7 @@ func ToJsonSafe[T any](obj T) (string, error) { } func ToJson[T any](obj T) string { - bytes, err := json.Marshal(obj) - - if err != nil { - // JSON is empty - } + bytes, _ := json.Marshal(obj) return string(bytes) } \ No newline at end of file diff --git a/utils/logger/logger.go b/utils/logger/logger.go index 871ba94..69d9a4a 100644 --- a/utils/logger/logger.go +++ b/utils/logger/logger.go @@ -45,8 +45,6 @@ func Init(level string) { if err != nil { fmt.Println("Encountered Error during Log.Init(): err.Error()") } - - Info("Initialized Logger with Level of ", logLevel.String()) } func getLogLevel(level string) zapcore.Level { @@ -68,6 +66,10 @@ func getLogLevel(level string) zapcore.Level { } } +func Level() string { + return _log.Level().String() +} + func Info(msg ...string) { _log.Info(strings.Join(msg, "")) } diff --git a/utils/query/query.go b/utils/query/query.go index 98a50ce..ab0d3bb 100644 --- a/utils/query/query.go +++ b/utils/query/query.go @@ -3,7 +3,7 @@ package query import ( "strings" - "github.com/codeshelldev/secured-signal-api/utils/safestrings" + stringutils "github.com/codeshelldev/secured-signal-api/utils/stringutils" ) func ParseRawQuery(raw string) map[string][]string { @@ -33,7 +33,7 @@ func ParseRawQuery(raw string) map[string][]string { func ParseTypedQueryValues(values []string) any { raw := values[len(values)-1] - return safestrings.ToType(raw) + return stringutils.ToType(raw) } func ParseTypedQuery(query string, matchPrefix string) (map[string]any) { diff --git a/utils/safestrings/safestrings.go b/utils/stringutils/stringutils.go similarity index 95% rename from utils/safestrings/safestrings.go rename to utils/stringutils/stringutils.go index 811e7b7..1857ee7 100644 --- a/utils/safestrings/safestrings.go +++ b/utils/stringutils/stringutils.go @@ -5,7 +5,7 @@ import ( "strconv" "strings" - "github.com/codeshelldev/secured-signal-api/utils" + jsonutils "github.com/codeshelldev/secured-signal-api/utils/jsonutils" ) func ToType(str string) any { @@ -13,7 +13,7 @@ func ToType(str string) any { //* Try JSON if IsEnclosedBy(cleaned, `[`, `]`) || IsEnclosedBy(cleaned, `{`, `}`) { - data, err := utils.GetJsonSafe[any](str) + data, err := jsonutils.GetJsonSafe[any](str) if data != nil && err == nil { return data