Skip to content

Commit

Permalink
[TT-11909]: Added Session Lifetime to OAS (#6835)
Browse files Browse the repository at this point in the history
### **User description**
<details open>
<summary><a href="https://tyktech.atlassian.net/browse/TT-11909"
title="TT-11909" target="_blank">TT-11909</a></summary>
  <br />
  <table>
    <tr>
      <th>Summary</th>
      <td>[OAS] Session lifetime </td>
    </tr>
    <tr>
      <th>Type</th>
      <td>
<img alt="Story"
src="https://tyktech.atlassian.net/rest/api/2/universal_avatar/view/type/issuetype/avatar/10315?size=medium"
/>
        Story
      </td>
    </tr>
    <tr>
      <th>Status</th>
      <td>In Dev</td>
    </tr>
    <tr>
      <th>Points</th>
      <td>N/A</td>
    </tr>
    <tr>
      <th>Labels</th>
      <td>-</td>
    </tr>
  </table>
</details>
<!--
  do not remove this marker as it will break jira-lint's functionality.
  added_by_jira_lint
-->

---

<!-- Provide a general summary of your changes in the Title above -->

## Description

<!-- Describe your changes in detail -->
[TT-1909](https://tyktech.atlassian.net/browse/TT-11909)

## Related Issue

<!-- This project only accepts pull requests related to open issues. -->
<!-- If suggesting a new feature or change, please discuss it in an
issue first. -->
<!-- If fixing a bug, there should be an issue describing it with steps
to reproduce. -->
<!-- OSS: Please link to the issue here. Tyk: please create/link the
JIRA ticket. -->

## Motivation and Context

<!-- Why is this change required? What problem does it solve? -->

## How This Has Been Tested

<!-- Please describe in detail how you tested your changes -->
<!-- Include details of your testing environment, and the tests -->
<!-- you ran to see how your change affects other areas of the code,
etc. -->
<!-- This information is helpful for reviewers and QA. -->

## Screenshots (if appropriate)

## Types of changes

<!-- What types of changes does your code introduce? Put an `x` in all
the boxes that apply: -->

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Refactoring or add test (improvements in base code or adds test
coverage to functionality)

## Checklist

<!-- Go over all the following points, and put an `x` in all the boxes
that apply -->
<!-- If there are no documentation updates required, mark the item as
checked. -->
<!-- Raise up any additional concerns not covered by the checklist. -->

- [ ] I ensured that the documentation is up to date
- [ ] I explained why this PR updates go.mod in detail with reasoning
why it's required
- [ ] I would like a code coverage CI quality gate exception and have
explained why


[TT-1909]:
https://tyktech.atlassian.net/browse/TT-1909?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ


___

### **PR Type**
Enhancement, Tests


___

### **Description**
- Added `session_lifetime_disabled` field to API definition.

- Introduced `KeyRetentionPeriod` struct for token TTL management.

- Updated OpenAPI schema to include `keyRetentionPeriod`.

- Enhanced migration and linter tests to cover new fields.


___



### **Changes walkthrough** 📝
<table><thead><tr><th></th><th align="left">Relevant
files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><table>
<tr>
  <td>
    <details>
<summary><strong>api_definitions.go</strong><dd><code>Introduced
`session_lifetime_disabled` field</code>&nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
</dd></summary>
<hr>

apidef/api_definitions.go

<li>Added <code>session_lifetime_disabled</code> field to API
definition.<br> <li> Enhanced session lifetime management capabilities.


</details>


  </td>
<td><a
href="https://github.com/TykTechnologies/tyk/pull/6835/files#diff-9961ccc89a48d32db5b47ba3006315ef52f6e5007fb4b09f8c5d6d299c669d67">+1/-0</a>&nbsp;
&nbsp; &nbsp; </td>

</tr>

<tr>
  <td>
    <details>
<summary><strong>migration.go</strong><dd><code>Updated migration logic
for session lifetime</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></summary>
<hr>

apidef/migration.go

- Set `SessionLifetimeDisabled` flag in migration logic.


</details>


  </td>
<td><a
href="https://github.com/TykTechnologies/tyk/pull/6835/files#diff-e1d9b55a26f9d6225d56d6f0161959217308e5ad4d6934e7d7df4595d9c2a130">+1/-0</a>&nbsp;
&nbsp; &nbsp; </td>

</tr>

<tr>
  <td>
    <details>
<summary><strong>authentication.go</strong><dd><code>Introduced
`KeyRetentionPeriod` for token TTL</code>&nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></summary>
<hr>

apidef/oas/authentication.go

<li>Added <code>KeyRetentionPeriod</code> struct for token TTL
management.<br> <li> Implemented <code>Fill</code> and
<code>ExtractTo</code> methods for <code>KeyRetentionPeriod</code>.


</details>


  </td>
<td><a
href="https://github.com/TykTechnologies/tyk/pull/6835/files#diff-e51c9d24d4235e7cc53048cc1d92967d177585ba5e073f14876308a97bef6326">+35/-0</a>&nbsp;
&nbsp; </td>

</tr>

<tr>
  <td>
    <details>
<summary><strong>x-tyk-api-gateway.json</strong><dd><code>Updated
OpenAPI schema for `keyRetentionPeriod`</code>&nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></summary>
<hr>

apidef/oas/schema/x-tyk-api-gateway.json

<li>Extended OpenAPI schema with <code>keyRetentionPeriod</code>
definition.<br> <li> Defined properties and validation for
<code>keyRetentionPeriod</code>.


</details>


  </td>
<td><a
href="https://github.com/TykTechnologies/tyk/pull/6835/files#diff-78828969c0c04cc1a776dfc93a8bad3c499a8c83e6169f83e96d090bed3e7dd0">+16/-0</a>&nbsp;
&nbsp; </td>

</tr>

<tr>
  <td>
    <details>
<summary><strong>schema.json</strong><dd><code>Updated schema with
`session_lifetime_disabled`</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></summary>
<hr>

apidef/schema.json

- Added `session_lifetime_disabled` field to schema.


</details>


  </td>
<td><a
href="https://github.com/TykTechnologies/tyk/pull/6835/files#diff-32c8b876e77d1639afb2d20c37b74ed9e149b72cc7de429def13d3d454e075f3">+3/-0</a>&nbsp;
&nbsp; &nbsp; </td>

</tr>
</table></td></tr><tr><td><strong>Tests</strong></td><td><table>
<tr>
  <td>
    <details>
<summary><strong>migration_test.go</strong><dd><code>Enhanced migration
tests for session lifetime</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></summary>
<hr>

apidef/migration_test.go

- Added test coverage for `SessionLifetimeDisabled` flag.


</details>


  </td>
<td><a
href="https://github.com/TykTechnologies/tyk/pull/6835/files#diff-d79d77f814074b9e483554e36687e22fda759045141c3b094b039428744ff94c">+1/-0</a>&nbsp;
&nbsp; &nbsp; </td>

</tr>

<tr>
  <td>
    <details>
<summary><strong>linter_test.go</strong><dd><code>Added linter test for
`KeyRetentionPeriod`</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
</dd></summary>
<hr>

apidef/oas/linter_test.go

- Updated linter tests to include `KeyRetentionPeriod`.


</details>


  </td>
<td><a
href="https://github.com/TykTechnologies/tyk/pull/6835/files#diff-b92239afd81e77a829fe7fe8410044dfd4dfda525d17dbf5f8811714a9c986d3">+1/-0</a>&nbsp;
&nbsp; &nbsp; </td>

</tr>
</table></td></tr></tr></tbody></table>

___

> 💡 **PR-Agent usage**: Comment `/help "your question"` on any pull
request to receive relevant information

---------

Co-authored-by: Tit Petric <[email protected]>
  • Loading branch information
kofoworola and titpetric authored Jan 17, 2025
1 parent 155e11b commit 4070fe0
Show file tree
Hide file tree
Showing 8 changed files with 87 additions and 1 deletion.
1 change: 1 addition & 0 deletions apidef/api_definitions.go
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,7 @@ type APIDefinition struct {
CacheOptions CacheOptions `bson:"cache_options" json:"cache_options"`
SessionLifetimeRespectsKeyExpiration bool `bson:"session_lifetime_respects_key_expiration" json:"session_lifetime_respects_key_expiration,omitempty"`
SessionLifetime int64 `bson:"session_lifetime" json:"session_lifetime"`
SessionLifetimeDisabled bool `bson:"session_lifetime_disabled" json:"session_lifetime_disabled"`
Active bool `bson:"active" json:"active"`
Internal bool `bson:"internal" json:"internal"`
AuthProvider AuthProviderMeta `bson:"auth_provider" json:"auth_provider"`
Expand Down
1 change: 1 addition & 0 deletions apidef/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,7 @@ func (a *APIDefinition) SetDisabledFlags() {
a.Proxy.ServiceDiscovery.CacheDisabled = true
a.UptimeTests.Config.ServiceDiscovery.CacheDisabled = true
a.DisableExpireAnalytics = true
a.SessionLifetimeDisabled = true

for i := 0; i < len(a.CustomMiddleware.Pre); i++ {
a.CustomMiddleware.Pre[i].Disabled = true
Expand Down
1 change: 1 addition & 0 deletions apidef/migration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,7 @@ func TestSetDisabledFlags(t *testing.T) {
DomainDisabled: true,
CustomMiddlewareBundleDisabled: true,
ConfigDataDisabled: true,
SessionLifetimeDisabled: true,
Proxy: ProxyConfig{
ServiceDiscovery: ServiceDiscoveryConfiguration{
CacheDisabled: true,
Expand Down
56 changes: 56 additions & 0 deletions apidef/oas/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"reflect"
"sort"
"time"

"github.com/getkin/kin-openapi/openapi3"
"github.com/mitchellh/mapstructure"
Expand Down Expand Up @@ -57,6 +58,45 @@ type Authentication struct {

// SecuritySchemes contains security schemes definitions.
SecuritySchemes SecuritySchemes `bson:"securitySchemes,omitempty" json:"securitySchemes,omitempty"`

// KeyRetentionPeriod contains configuration for key retention.
KeyRetentionPeriod *KeyRetentionPeriod `bson:"keyRetentionPeriod,omitempty" json:"keyRetentionPeriod,omitempty"`
}

// KeyRetentionPeriod contains configuration for key retention.
type KeyRetentionPeriod struct {
// Enabled enables Key retention for the API
//
// Tyk classic API definition: `disable_expire_analytics`.
Enabled bool `bson:"enabled,omitempty" json:"enabled,omitempty"`
// Value configures the expiry interval for a Key.
// The value is a string that specifies the interval in a compact form,
// where hours, minutes and seconds are denoted by 'h', 'm' and 's' respectively.
// Multiple units can be combined to represent the duration.
//
// Examples of valid shorthand notations:
// - "1h" : one hour
// - "20m" : twenty minutes
// - "30s" : thirty seconds
// - "1m29s": one minute and twenty-nine seconds
// - "1h30m" : one hour and thirty minutes
//
// An empty value is interpreted as "0s"
//
// Tyk classic API definition: `expire_analytics_after`.
Value ReadableDuration `bson:"value" json:"value"`
}

// Fill fills *KeyRetentionPeriod from apidef.APIDefinition.
func (k *KeyRetentionPeriod) Fill(api apidef.APIDefinition) {
k.Enabled = !api.SessionLifetimeDisabled
k.Value = ReadableDuration(time.Duration(api.ExpireAnalyticsAfter) * time.Second)
}

// ExtractTo extracts *Authentication into *apidef.APIDefinition.
func (k *KeyRetentionPeriod) ExtractTo(api *apidef.APIDefinition) {
api.SessionLifetimeDisabled = !k.Enabled
api.SessionLifetime = int64(k.Value.Seconds())
}

// Fill fills *Authentication from apidef.APIDefinition.
Expand All @@ -75,6 +115,14 @@ func (a *Authentication) Fill(api apidef.APIDefinition) {
a.Custom = nil
}

if a.KeyRetentionPeriod == nil {
a.KeyRetentionPeriod = &KeyRetentionPeriod{}
}
a.KeyRetentionPeriod.Fill(api)
if ShouldOmit(a.KeyRetentionPeriod) {
a.KeyRetentionPeriod = nil
}

if api.AuthConfigs == nil || len(api.AuthConfigs) == 0 {
return
}
Expand Down Expand Up @@ -126,6 +174,14 @@ func (a *Authentication) ExtractTo(api *apidef.APIDefinition) {
}

a.Custom.ExtractTo(api)

if a.KeyRetentionPeriod == nil {
a.KeyRetentionPeriod = &KeyRetentionPeriod{}
defer func() {
a.KeyRetentionPeriod = nil
}()
}
a.KeyRetentionPeriod.ExtractTo(api)
}

// SecuritySchemes holds security scheme values, filled with Import().
Expand Down
1 change: 1 addition & 0 deletions apidef/oas/linter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ func TestXTykGateway_Lint(t *testing.T) {
}

settings.Upstream.RateLimit.Per = ReadableDuration(10 * time.Second)
settings.Server.Authentication.KeyRetentionPeriod.Value = ReadableDuration(10 * time.Second)

settings.Upstream.Authentication = &UpstreamAuth{
Enabled: false,
Expand Down
10 changes: 9 additions & 1 deletion apidef/oas/oas_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ func TestOAS_ExtractTo_ResetAPIDefinition(t *testing.T) {
a.DoNotTrack = false
a.IPAccessControlDisabled = false
a.DisableExpireAnalytics = false
a.SessionLifetimeDisabled = false

// deprecated fields
a.Auth = apidef.AuthConfig{}
Expand Down Expand Up @@ -254,7 +255,6 @@ func TestOAS_ExtractTo_ResetAPIDefinition(t *testing.T) {
"APIDefinition.Proxy.Transport.ProxyURL",
"APIDefinition.DisableQuota",
"APIDefinition.SessionLifetimeRespectsKeyExpiration",
"APIDefinition.SessionLifetime",
"APIDefinition.AuthProvider.Name",
"APIDefinition.AuthProvider.StorageEngine",
"APIDefinition.AuthProvider.Meta[0]",
Expand Down Expand Up @@ -1055,6 +1055,10 @@ func TestMigrateAndFillOAS_CustomPluginAuth(t *testing.T) {
Path: "/path/to/plugin",
},
},
KeyRetentionPeriod: &KeyRetentionPeriod{
Enabled: true,
Value: 0,
},
}

assert.Equal(t, expectedAuthentication, *migratedAPI.OAS.GetTykExtension().Server.Authentication)
Expand Down Expand Up @@ -1105,6 +1109,10 @@ func TestMigrateAndFillOAS_CustomPluginAuth(t *testing.T) {
},
},
},
KeyRetentionPeriod: &KeyRetentionPeriod{
Enabled: true,
Value: 0,
},
}

assert.Equal(t, expectedAuthentication, *migratedAPI.OAS.GetTykExtension().Server.Authentication)
Expand Down
15 changes: 15 additions & 0 deletions apidef/oas/schema/x-tyk-api-gateway.json
Original file line number Diff line number Diff line change
Expand Up @@ -1203,6 +1203,21 @@
]
}
}
},
"keyRetentionPeriod": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
},
"value": {
"type": "string",
"pattern": "^(\\d+h)?(\\d+m)?(\\d+s)?$"
}
},
"required": [
"enabled"
]
}
},
"required": [
Expand Down
3 changes: 3 additions & 0 deletions apidef/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@
"do_not_track": {
"type": "boolean"
},
"session_lifetime_disabled": {
"type": "boolean"
},
"enable_jwt": {
"type": "boolean"
},
Expand Down

0 comments on commit 4070fe0

Please sign in to comment.