Skip to content

Commit

Permalink
chore: format code
Browse files Browse the repository at this point in the history
  • Loading branch information
GZTimeWalker committed Sep 24, 2023
1 parent 43961e8 commit 6051a12
Show file tree
Hide file tree
Showing 16 changed files with 83 additions and 63 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,14 @@ All notable changes to [**GZCTF**](https://github.com/GZTimeWalker/GZCTF) will b

### 🐛 Bug Fixes

- cannot list captured traffic - ([43961e](https://github.com/GZTimeWalker/GZCTF/commit/43961e)) by **GZTime**
- cannot enable traffic capture for static container challenge - ([dc8972](https://github.com/GZTimeWalker/GZCTF/commit/dc8972)) by **GZTime**
- cannot empty post summary & content - ([3feb43](https://github.com/GZTimeWalker/GZCTF/commit/3feb43)) by **GZTime**

### ⚙️ Miscellaneous Tasks

- format code - ([9d0da3](https://github.com/GZTimeWalker/GZCTF/commit/9d0da3)) by **GZTime**

---
## [0.17.4](https://github.com/GZTimeWalker/GZCTF/compare/v0.17.3..v0.17.4) - 2023-09-22

Expand Down
14 changes: 7 additions & 7 deletions src/GZCTF/Controllers/GameController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -887,13 +887,13 @@ public async Task<IActionResult> CreateContainer([FromRoute] int id, [FromRoute]

return await instanceRepository.CreateContainer(instance, context.Participation!.Team, context.User!,
context.Game!.ContainerCountLimit, token) switch
{
null or (TaskStatus.Failed, null) => BadRequest(new RequestResponse("题目创建容器失败")),
(TaskStatus.Denied, null) => BadRequest(
new RequestResponse($"队伍容器数目不能超过 {context.Game.ContainerCountLimit}")),
(TaskStatus.Success, var x) => Ok(ContainerInfoModel.FromContainer(x!)),
_ => throw new NotImplementedException()
};
{
null or (TaskStatus.Failed, null) => BadRequest(new RequestResponse("题目创建容器失败")),
(TaskStatus.Denied, null) => BadRequest(
new RequestResponse($"队伍容器数目不能超过 {context.Game.ContainerCountLimit}")),
(TaskStatus.Success, var x) => Ok(ContainerInfoModel.FromContainer(x!)),
_ => throw new NotImplementedException()
};
}

/// <summary>
Expand Down
70 changes: 35 additions & 35 deletions src/GZCTF/Middlewares/RateLimiter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,29 +37,14 @@ public enum LimitPolicy

public static RateLimiterOptions GetRateLimiterOptions() =>
new RateLimiterOptions
{
RejectionStatusCode = StatusCodes.Status429TooManyRequests,
GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
{
RejectionStatusCode = StatusCodes.Status429TooManyRequests,
GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
{
var userId = context?.User.FindFirstValue(ClaimTypes.NameIdentifier);
var userId = context?.User.FindFirstValue(ClaimTypes.NameIdentifier);

if (userId is not null)
return RateLimitPartition.GetSlidingWindowLimiter(userId,
key => new()
{
PermitLimit = 150,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 60,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
SegmentsPerWindow = 6
});

IPAddress? address = context?.Connection?.RemoteIpAddress;

if (address is null || IPAddress.IsLoopback(address))
return RateLimitPartition.GetNoLimiter(IPAddress.Loopback.ToString());

return RateLimitPartition.GetSlidingWindowLimiter(address.ToString(),
if (userId is not null)
return RateLimitPartition.GetSlidingWindowLimiter(userId,
key => new()
{
PermitLimit = 150,
Expand All @@ -68,24 +53,39 @@ public static RateLimiterOptions GetRateLimiterOptions() =>
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
SegmentsPerWindow = 6
});
}),
OnRejected = async (context, cancellationToken) =>
{
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
context.HttpContext.Response.ContentType = MediaTypeNames.Application.Json;

var afterSec = (int)TimeSpan.FromMinutes(1).TotalSeconds;
IPAddress? address = context?.Connection?.RemoteIpAddress;

if (address is null || IPAddress.IsLoopback(address))
return RateLimitPartition.GetNoLimiter(IPAddress.Loopback.ToString());

return RateLimitPartition.GetSlidingWindowLimiter(address.ToString(),
key => new()
{
PermitLimit = 150,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 60,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
SegmentsPerWindow = 6
});
}),
OnRejected = async (context, cancellationToken) =>
{
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
context.HttpContext.Response.ContentType = MediaTypeNames.Application.Json;

var afterSec = (int)TimeSpan.FromMinutes(1).TotalSeconds;

if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
afterSec = (int)retryAfter.TotalSeconds;
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
afterSec = (int)retryAfter.TotalSeconds;

context.HttpContext.Response.Headers.RetryAfter = afterSec.ToString(NumberFormatInfo.InvariantInfo);
await context.HttpContext.Response.WriteAsJsonAsync(
new RequestResponse($"Too many requests, retry after {afterSec} seconds.",
StatusCodes.Status429TooManyRequests
), cancellationToken);
}
context.HttpContext.Response.Headers.RetryAfter = afterSec.ToString(NumberFormatInfo.InvariantInfo);
await context.HttpContext.Response.WriteAsJsonAsync(
new RequestResponse($"Too many requests, retry after {afterSec} seconds.",
StatusCodes.Status429TooManyRequests
), cancellationToken);
}
}
.AddConcurrencyLimiter(nameof(LimitPolicy.Concurrency), options =>
{
options.PermitLimit = 1;
Expand Down
2 changes: 1 addition & 1 deletion src/GZCTF/Models/Request/Edit/ChallengeEditDetailModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ internal static ChallengeEditDetailModel FromChallenge(Challenge chal) =>
Attachment = chal.Attachment,
TestContainer = chal.TestContainer is null ? null : ContainerInfoModel.FromContainer(chal.TestContainer),
Flags = (from flag in chal.Flags
select FlagInfoModel.FromFlagContext(flag))
select FlagInfoModel.FromFlagContext(flag))
.ToArray()
};

Expand Down
7 changes: 4 additions & 3 deletions src/GZCTF/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -355,11 +355,12 @@ public static IActionResult InvalidModelStateHandler(ActionContext context)

if (context.ModelState.ErrorCount <= 0)
return new JsonResult(
new RequestResponse(errors is not null && errors.Length > 0 ? errors : "校验失败,请检查输入。")) { StatusCode = 400 };
new RequestResponse(errors is not null && errors.Length > 0 ? errors : "校验失败,请检查输入。"))
{ StatusCode = 400 };

errors = (from val in context.ModelState.Values
where val.Errors.Count > 0
select val.Errors.FirstOrDefault()?.ErrorMessage).FirstOrDefault();
where val.Errors.Count > 0
select val.Errors.FirstOrDefault()?.ErrorMessage).FirstOrDefault();

return new JsonResult(new RequestResponse(errors is not null && errors.Length > 0 ? errors : "校验失败,请检查输入。")) { StatusCode = 400 };
}
Expand Down
4 changes: 3 additions & 1 deletion src/GZCTF/Repositories/ChallengeRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ public async Task UpdateAttachment(Challenge challenge, AttachmentCreateModel mo
? null
: new()
{
Type = model.AttachmentType, LocalFile = await fileRepository.GetFileByHash(model.FileHash, token), RemoteUrl = model.RemoteUrl
Type = model.AttachmentType,
LocalFile = await fileRepository.GetFileByHash(model.FileHash, token),
RemoteUrl = model.RemoteUrl
};

await DeleteAllAttachment(challenge, false, token);
Expand Down
3 changes: 2 additions & 1 deletion src/GZCTF/Repositories/GameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,8 @@ static IEnumerable<TimeLine> GenTimeLine(IEnumerable<ChallengeItem> items)
score += i.Score;
return new TimeLine
{
Score = score, Time = i.SubmitTimeUTC!.Value // 此处不为 null
Score = score,
Time = i.SubmitTimeUTC!.Value // 此处不为 null
};
});
}
Expand Down
3 changes: 2 additions & 1 deletion src/GZCTF/Services/ConfigService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ async Task SaveConfigInternal(HashSet<Config> configs, CancellationToken token =

static bool IsArrayLikeInterface(Type type)
{
if (!type.IsInterface || !type.IsConstructedGenericType) return false;
if (!type.IsInterface || !type.IsConstructedGenericType)
return false;

Type genericTypeDefinition = type.GetGenericTypeDefinition();
return genericTypeDefinition == typeof(IEnumerable<>)
Expand Down
4 changes: 3 additions & 1 deletion src/GZCTF/Services/Container/Manager/DockerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,9 @@ CreateContainerParameters GetCreateContainerParameters(ContainerConfig config) =
Env = config.Flag is null ? Array.Empty<string>() : new[] { $"GZCTF_FLAG={config.Flag}" },
HostConfig = new()
{
Memory = config.MemoryLimit * 1024 * 1024, CPUPercent = config.CPUCount * 10, NetworkMode = _meta.Config.ChallengeNetwork
Memory = config.MemoryLimit * 1024 * 1024,
CPUPercent = config.CPUCount * 10,
NetworkMode = _meta.Config.ChallengeNetwork
}
};
}
4 changes: 3 additions & 1 deletion src/GZCTF/Services/Container/Manager/K8sManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ public K8sManager(IContainerProvider<Kubernetes, K8sMetadata> provider, ILogger<
NamespaceProperty = options.Namespace,
Labels = new Dictionary<string, string>
{
["ctf.gzti.me/ResourceId"] = name, ["ctf.gzti.me/TeamId"] = config.TeamId, ["ctf.gzti.me/UserId"] = config.UserId
["ctf.gzti.me/ResourceId"] = name,
["ctf.gzti.me/TeamId"] = config.TeamId,
["ctf.gzti.me/UserId"] = config.UserId
}
},
Spec = new V1PodSpec
Expand Down
2 changes: 1 addition & 1 deletion src/GZCTF/Services/Container/Manager/SwarmManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public async Task DestroyContainerAsync(Models.Data.Container container, Cancell
ServiceCreateParameters parameters = GetServiceCreateParameters(config);
var retry = 0;
ServiceCreateResponse? serviceRes;
CreateContainer:
CreateContainer:
try
{
serviceRes = await _client.Swarm.CreateServiceAsync(parameters, token);
Expand Down
4 changes: 3 additions & 1 deletion src/GZCTF/Services/Container/Provider/DockerProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ public DockerProvider(IOptions<ContainerProvider> options, IOptions<RegistryConf
{
_dockerMeta = new()
{
Config = options.Value.DockerConfig ?? new(), PortMappingType = options.Value.PortMappingType, PublicEntry = options.Value.PublicEntry
Config = options.Value.DockerConfig ?? new(),
PortMappingType = options.Value.PortMappingType,
PublicEntry = options.Value.PublicEntry
};

DockerClientConfiguration cfg = string.IsNullOrEmpty(_dockerMeta.Config.Uri)
Expand Down
4 changes: 3 additions & 1 deletion src/GZCTF/Services/Container/Provider/K8sProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ public K8sProvider(IOptions<RegistryConfig> registry, IOptions<ContainerProvider
{
_k8sMetadata = new()
{
Config = options.Value.K8sConfig ?? new(), PortMappingType = options.Value.PortMappingType, PublicEntry = options.Value.PublicEntry
Config = options.Value.K8sConfig ?? new(),
PortMappingType = options.Value.PortMappingType,
PublicEntry = options.Value.PublicEntry
};

if (!File.Exists(_k8sMetadata.Config.KubeConfig))
Expand Down
3 changes: 2 additions & 1 deletion src/GZCTF/Utils/Codec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ public static string BytesToHex(byte[] bytes, bool useLower = true)
public static byte[] Xor(byte[] data, byte[] xor)
{
var res = new byte[data.Length];
for (var i = 0; i < data.Length; ++i) res[i] = (byte)(data[i] ^ xor[i % xor.Length]);
for (var i = 0; i < data.Length; ++i)
res[i] = (byte)(data[i] ^ xor[i % xor.Length]);
return res;
}

Expand Down
14 changes: 7 additions & 7 deletions src/GZCTF/Utils/ExcelHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,13 @@ static int[] WriteBoardHeader(ISheet sheet, ICellStyle style, ScoreboardModel sc
}

foreach (KeyValuePair<ChallengeTag, IEnumerable<ChallengeInfo>> type in scoreboard.Challenges)
foreach (ChallengeInfo chall in type.Value)
{
ICell? cell = row.CreateCell(colIndex++);
cell.SetCellValue(chall.Title);
cell.CellStyle = style;
challIds.Add(chall.Id);
}
foreach (ChallengeInfo chall in type.Value)
{
ICell? cell = row.CreateCell(colIndex++);
cell.SetCellValue(chall.Title);
cell.CellStyle = style;
challIds.Add(chall.Id);
}

return challIds.ToArray();
}
Expand Down
3 changes: 2 additions & 1 deletion src/GZCTF/Utils/FilePath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ internal static void EnsureDirs()
foreach (DirType type in Enum.GetValues<DirType>())
{
var path = Path.Combine(Base, type.ToString().ToLower());
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
}

Expand Down

0 comments on commit 6051a12

Please sign in to comment.