<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anass Guendef on Medium]]></title>
        <description><![CDATA[Stories by Anass Guendef on Medium]]></description>
        <link>https://medium.com/@anassguendef?source=rss-2f0c7102fced------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GSl6a18wc4V-IJjmu72AMQ.jpeg</url>
            <title>Stories by Anass Guendef on Medium</title>
            <link>https://medium.com/@anassguendef?source=rss-2f0c7102fced------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:05:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anassguendef/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Execute Angular Guards Sequentially and in Order]]></title>
            <link>https://medium.com/@anassguendef/execute-angular-guards-sequentially-and-in-order-9fa5367fa848?source=rss-2f0c7102fced------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fa5367fa848</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-guards]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Anass Guendef]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 10:06:22 GMT</pubDate>
            <atom:updated>2025-12-02T10:06:22.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*-9XCYib9HkLuF-R6Odb-jw.jpeg" /></figure><h3>TL;DR</h3><p>By default, Angular runs all guards for a route <strong>in parallel</strong>, stopping at the first blocking result. This utility wraps that behavior to <strong>force sequential execution</strong> in the <strong>order you define</strong>: continue as long as each guard returns true, and stop immediately if a guard returns false or an UrlTree (redirect).</p><pre><br>canActivate: [<br>  OrderedAsyncGuardUtils.orderedAsyncGuards([AuthGuard, RoleGuard, BusinessGuard])<br>]</pre><h3>The Problem</h3><p>In complex apps, you often need to <strong>control the execution order</strong> of guards to:</p><ul><li>Ensure <strong>prerequisites</strong> (e.g., authentication before role checks),</li><li>Avoid <strong>unnecessary calls</strong> (don’t hit APIs if a previous guard already blocks),</li><li>Make navigation logic <strong>predictable and readable</strong>.</li></ul><p>Angular runs guards <strong>in parallel</strong> by default. Even though it stops at the first blocking result, the <strong>order is not guaranteed</strong>, and multiple guards may run simultaneously.</p><h3>The Solution</h3><p>OrderedAsyncGuardUtils lets you:</p><ul><li><strong>Instantiate</strong> guards via Angular DI (inject(...)),</li><li><strong>Normalize</strong> return types (boolean | UrlTree | Promise | Observable) into Observable&lt;boolean | UrlTree&gt;,</li><li><strong>Chain them sequentially</strong> using RxJS (concatMap),</li><li><strong>Stop immediately</strong> on false or UrlTree,</li><li><strong>Return</strong> the last emitted value (true, false, or UrlTree).</li></ul><h3>API Overview</h3><h4>Guard Interface</h4><pre><br>export interface OrderedGuard {<br>  canActivate(<br>    route: ActivatedRouteSnapshot,<br>    state: RouterStateSnapshot<br>  ): boolean | UrlTree | Observable&lt;boolean | UrlTree&gt; | Promise&lt;boolean | UrlTree&gt;;<br>}</pre><h4>Guard Class Type</h4><pre>export type GuardClass = { new (...args: any[]): OrderedGuard };</pre><h4>Utility Method</h4><pre>OrderedAsyncGuardUtils.orderedAsyncGuards(guards: GuardClass[]): CanActivateFn;</pre><h3>Example Usage</h3><h4>1) Three simple guards</h4><pre><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class AuthGuard implements OrderedGuard {<br>  constructor(private auth: AuthService) {}<br>  canActivate(): boolean | UrlTree {<br>    return this.auth.isLoggedIn() ? true : this.auth.redirectToLoginTree();<br>  }<br>}<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class RoleGuard implements OrderedGuard {<br>  constructor(private roles: RoleService) {}<br>  canActivate(route: ActivatedRouteSnapshot): boolean {<br>    return this.roles.hasRequiredRoles(route.data[&#39;roles&#39;]);<br>  }<br>}<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class BusinessGuard implements OrderedGuard {<br>  constructor(private business: BusinessService) {}<br>  async canActivate(): Promise&lt;boolean | UrlTree&gt; {<br>    const ok = await this.business.checkPrerequisites();<br>    return ok ? true : this.business.redirectToPrereqTree();<br>  }<br>}</pre><h4>2) Route configuration with ordered guards</h4><pre><br>{<br>  path: &#39;secure-area&#39;,<br>  component: SecureComponent,<br>  data: { roles: [&#39;ADMIN&#39;, &#39;EDITOR&#39;] },<br>  canActivate: [<br>    OrderedAsyncGuardUtils.orderedAsyncGuards([AuthGuard, RoleGuard, BusinessGuard])<br>  ]<br>}</pre><p><strong>Result:</strong></p><ol><li>AuthGuard runs first.</li><li>If true, RoleGuard runs next.</li><li>If true, BusinessGuard runs last.</li><li>If any guard returns false or UrlTree, execution stops and that value is returned.</li></ol><h3>Core Utility Code</h3><pre><br>function toObservable(<br>  value: boolean | UrlTree | Observable&lt;boolean | UrlTree&gt; | Promise&lt;boolean | UrlTree&gt;<br>): Observable&lt;boolean | UrlTree&gt; {<br>  if (isObservable(value)) return value as Observable&lt;boolean | UrlTree&gt;;<br>  if (value instanceof Promise) return from(value);<br>  return of(value);<br>}<br><br>export class OrderedAsyncGuardUtils {<br>  static orderedAsyncGuards(guards: GuardClass[]): CanActivateFn {<br>    return (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable&lt;boolean | UrlTree&gt; =&gt; {<br>      const instances = guards.map(g =&gt; inject(g)) as unknown as OrderedGuard[];<br>      return from(instances).pipe(<br>        concatMap(guard =&gt; toObservable(guard.canActivate(route, state))),<br>        takeWhile(result =&gt; result === true, true),<br>        last()<br>      );<br>    };<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fa5367fa848" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Guide to ID Obfuscation in Spring Boot REST APIs]]></title>
            <link>https://medium.com/@anassguendef/a-complete-guide-to-id-obfuscation-in-spring-boot-rest-apis-7d6e7b28fa5a?source=rss-2f0c7102fced------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d6e7b28fa5a</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[uuid]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[obfuscation]]></category>
            <dc:creator><![CDATA[Anass Guendef]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 14:46:16 GMT</pubDate>
            <atom:updated>2025-11-27T14:47:31.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G617q9Fpihifd4ee" /><figcaption>Photo by <a href="https://unsplash.com/@franckinjapan?utm_source=medium&amp;utm_medium=referral">Franck</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>When building REST APIs, exposing internal database IDs in URLs and JSON responses can pose security risks. This guide demonstrates how to implement automatic ID obfuscation using UUIDs in a Spring Boot application, converting technical IDs (Long, Integer, String) to deterministic UUIDs and back.</p><h3>Why Obfuscate IDs?</h3><ul><li><strong>Security</strong>: Prevents enumeration attacks where attackers guess sequential IDs</li><li><strong>Privacy</strong>: Hides internal data structure and record counts</li><li><strong>Consistency</strong>: Provides uniform ID format across your API</li><li><strong>Reversibility</strong>: Maintains bidirectional conversion for internal processing</li></ul><h3>Architecture Overview</h3><p>Our solution consists of several key components:</p><ol><li><strong>UUID Converter Service</strong>: Handles bidirectional conversion between IDs and UUIDs</li><li><strong>Custom Annotation</strong>: Marks fields/parameters for automatic obfuscation</li><li><strong>Jackson Serializers/Deserializers</strong>: Handles JSON conversion</li><li><strong>Argument Resolver</strong>: Processes obfuscated controller parameters</li></ol><h3>Step-by-Step Implementation</h3><h4>Step 1: Create the Obfuscation Annotation</h4><pre>package com.example.api.security.obfuscation;<br><br>import java.lang.annotation.ElementType;<br>import java.lang.annotation.Retention;<br>import java.lang.annotation.RetentionPolicy;<br>import java.lang.annotation.Target;<br><br>/**<br> * Annotation indicating that a field or parameter is obfuscated (encoded as UUID)<br> * and should be automatically de-obfuscated.<br> * <br> * Can be applied to:<br> * - Controller method parameters (@PathVariable or @RequestParam)<br> * - DTO fields (input/output)<br> */<br>@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface Obfuscated {<br>}</pre><h4>Step 2: Implement the UUID Converter Service</h4><p>Create a service that converts IDs to deterministic UUIDs:</p><pre>package com.example.api.security.obfuscation;<br><br>import java.nio.ByteBuffer;<br>import java.nio.charset.StandardCharsets;<br>import java.util.Arrays;<br>import java.util.UUID;<br>import org.springframework.stereotype.Service;<br><br>/**<br> * Service for converting identifiers (Long, Integer, String ≤ 15 chars) <br> * to deterministic and reversible UUIDs.<br> * <br> * UUID structure (128 bits = 16 bytes):<br> * - 1 byte: type marker (Long, Integer, String)<br> * - 15 bytes: data (padding + value)<br> */<br>@Service<br>public class UuidConverterService {<br><br>    // Constants<br>    private static final int UUID_SIZE = 16;<br>    protected static final int MAX_STRING_LENGTH = 15;<br>    <br>    // Type markers<br>    private static final byte TYPE_LONG = 1;<br>    private static final byte TYPE_INTEGER = 2;<br>    private static final byte TYPE_STRING = 3;<br>    <br>    // Positions and padding<br>    private static final int LONG_POSITION = 8;<br>    private static final int INTEGER_POSITION = 12;<br>    private static final int LONG_PADDING = 7;<br>    private static final int INTEGER_PADDING = 11;<br><br>    /**<br>     * Generic method to convert any supported type to UUID<br>     */<br>    public UUID toUuid(Object id) {<br>        if (id == null) {<br>            return null;<br>        }<br><br>        if (id instanceof Long) {<br>            return toUuid((Long) id);<br>        } else if (id instanceof Integer) {<br>            return toUuid((Integer) id);<br>        } else if (id instanceof String) {<br>            return toUuid((String) id);<br>        } else {<br>            throw new IllegalArgumentException(<br>                &quot;Unsupported type: &quot; + id.getClass().getName()<br>            );<br>        }<br>    }<br><br>    /**<br>     * Convert Long to deterministic UUID<br>     */<br>    protected UUID toUuid(Long id) {<br>        if (id == null) {<br>            return null;<br>        }<br><br>        ByteBuffer bb = ByteBuffer.wrap(new byte[UUID_SIZE]);<br>        bb.put(TYPE_LONG);<br>        bb.put(new byte[LONG_PADDING]);<br>        bb.putLong(id);<br><br>        return new UUID(bb.getLong(0), bb.getLong(8));<br>    }<br><br>    /**<br>     * Convert Integer to deterministic UUID<br>     */<br>    protected UUID toUuid(Integer id) {<br>        if (id == null) {<br>            return null;<br>        }<br><br>        ByteBuffer bb = ByteBuffer.wrap(new byte[UUID_SIZE]);<br>        bb.put(TYPE_INTEGER);<br>        bb.put(new byte[INTEGER_PADDING]);<br>        bb.putInt(id);<br><br>        return new UUID(bb.getLong(0), bb.getLong(LONG_POSITION));<br>    }<br><br>    /**<br>     * Convert String to deterministic UUID (max 15 UTF-8 bytes)<br>     */<br>    protected UUID toUuid(String id) {<br>        if (id == null) {<br>            return null;<br>        }<br><br>        byte[] stringBytes = id.getBytes(StandardCharsets.UTF_8);<br>        <br>        if (stringBytes.length &gt; MAX_STRING_LENGTH) {<br>            throw new IllegalArgumentException(<br>                &quot;String too long: max &quot; + MAX_STRING_LENGTH + <br>                &quot; bytes, received &quot; + stringBytes.length<br>            );<br>        }<br><br>        ByteBuffer bb = ByteBuffer.wrap(new byte[UUID_SIZE]);<br>        bb.put(TYPE_STRING);<br>        bb.put(stringBytes);<br><br>        return new UUID(bb.getLong(0), bb.getLong(LONG_POSITION));<br>    }<br><br>    /**<br>     * Retrieve the original value (Long, Integer, or String) from UUID<br>     */<br>    public Object toOriginal(UUID uuid) {<br>        if (uuid == null) {<br>            return null;<br>        }<br><br>        Class&lt;?&gt; type = detectType(uuid);<br>        <br>        if (type == null) {<br>            throw new IllegalArgumentException(<br>                &quot;UUID origin type not recognized&quot;<br>            );<br>        }<br><br>        if (type == Long.class) {<br>            return toLong(uuid);<br>        } else if (type == Integer.class) {<br>            return toInteger(uuid);<br>        } else {<br>            return toString(uuid);<br>        }<br>    }<br><br>    /**<br>     * Convert UUID back to Long<br>     */<br>    protected Long toLong(UUID uuid) {<br>        if (uuid == null) {<br>            return null;<br>        }<br><br>        ByteBuffer bb = reconstructBuffer(uuid);<br>        byte type = bb.get();<br>        <br>        if (type != TYPE_LONG) {<br>            throw new IllegalArgumentException(&quot;UUID not created from Long&quot;);<br>        }<br>        <br>        bb.position(LONG_POSITION);<br>        return bb.getLong();<br>    }<br><br>    /**<br>     * Convert UUID back to Integer<br>     */<br>    protected Integer toInteger(UUID uuid) {<br>        if (uuid == null) {<br>            return null;<br>        }<br><br>        ByteBuffer bb = reconstructBuffer(uuid);<br>        byte type = bb.get();<br>        <br>        if (type != TYPE_INTEGER) {<br>            throw new IllegalArgumentException(&quot;UUID not created from Integer&quot;);<br>        }<br>        <br>        bb.position(INTEGER_POSITION);<br>        return bb.getInt();<br>    }<br><br>    /**<br>     * Convert UUID back to String<br>     */<br>    protected String toString(UUID uuid) {<br>        if (uuid == null) {<br>            return null;<br>        }<br><br>        ByteBuffer bb = reconstructBuffer(uuid);<br>        byte type = bb.get();<br>        <br>        if (type != TYPE_STRING) {<br>            throw new IllegalArgumentException(&quot;UUID not created from String&quot;);<br>        }<br><br>        byte[] stringBytes = new byte[MAX_STRING_LENGTH];<br>        bb.get(stringBytes);<br><br>        // Find actual length (remove trailing zeros)<br>        int actualLength = MAX_STRING_LENGTH;<br>        for (int i = MAX_STRING_LENGTH - 1; i &gt;= 0; i--) {<br>            if (stringBytes[i] != 0) {<br>                break;<br>            }<br>            actualLength--;<br>        }<br><br>        return new String(<br>            Arrays.copyOf(stringBytes, actualLength), <br>            StandardCharsets.UTF_8<br>        );<br>    }<br><br>    /**<br>     * Detect the original type from UUID<br>     */<br>    protected Class&lt;?&gt; detectType(UUID uuid) {<br>        if (uuid == null) {<br>            return null;<br>        }<br><br>        ByteBuffer bb = reconstructBuffer(uuid);<br>        byte type = bb.get();<br><br>        switch (type) {<br>            case TYPE_LONG:<br>                return Long.class;<br>            case TYPE_INTEGER:<br>                return Integer.class;<br>            case TYPE_STRING:<br>                return String.class;<br>            default:<br>                return null;<br>        }<br>    }<br><br>    /**<br>     * Reconstruct ByteBuffer from UUID and reset position to zero<br>     */<br>    private static ByteBuffer reconstructBuffer(UUID uuid) {<br>        ByteBuffer bb = ByteBuffer.wrap(new byte[UUID_SIZE]);<br>        bb.putLong(uuid.getMostSignificantBits());<br>        bb.putLong(uuid.getLeastSignificantBits());<br>        bb.rewind();<br>        return bb;<br>    }<br>}</pre><h4>Step 3: Create Jackson Serializer</h4><p>Implement a custom Jackson serializer to automatically convert IDs to UUIDs in JSON responses:</p><pre>package com.example.api.security.obfuscation;<br><br>import java.io.IOException;<br>import java.util.UUID;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import com.fasterxml.jackson.core.JsonGenerator;<br>import com.fasterxml.jackson.databind.BeanProperty;<br>import com.fasterxml.jackson.databind.JsonSerializer;<br>import com.fasterxml.jackson.databind.SerializerProvider;<br>import com.fasterxml.jackson.databind.ser.ContextualSerializer;<br>import com.fasterxml.jackson.databind.ser.std.StdSerializer;<br><br>/**<br> * Jackson serializer to automatically obfuscate fields annotated with @Obfuscated<br> */<br>public class UuidSerializer extends StdSerializer&lt;Object&gt; <br>        implements ContextualSerializer {<br><br>    private static final long serialVersionUID = 1L;<br>    private final transient UuidConverterService converterService;<br><br>    @Autowired<br>    public UuidSerializer(UuidConverterService converterService) {<br>        super(Object.class);<br>        this.converterService = converterService;<br>    }<br><br>    @Override<br>    public void serialize(Object value, JsonGenerator gen, <br>                         SerializerProvider provider) throws IOException {<br>        if (value == null) {<br>            gen.writeNull();<br>            return;<br>        }<br><br>        UUID obfuscated = converterService.toUuid(value);<br>        gen.writeString(obfuscated.toString());<br>    }<br><br>    @Override<br>    public JsonSerializer&lt;?&gt; createContextual(SerializerProvider prov, <br>                                              BeanProperty property) {<br>        if (property != null) {<br>            Obfuscated annotation = property.getAnnotation(Obfuscated.class);<br>            if (annotation != null) {<br>                return new UuidSerializer(converterService);<br>            }<br>        }<br>        return this;<br>    }<br>}</pre><h4>Step 4: Create Jackson Deserializer</h4><p>Implement the corresponding deserializer to convert UUIDs back to original IDs:</p><pre>package com.example.api.security.obfuscation;<br><br>import java.io.IOException;<br>import java.util.UUID;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import com.fasterxml.jackson.core.JsonParser;<br>import com.fasterxml.jackson.databind.BeanProperty;<br>import com.fasterxml.jackson.databind.DeserializationContext;<br>import com.fasterxml.jackson.databind.JsonDeserializer;<br>import com.fasterxml.jackson.databind.deser.ContextualDeserializer;<br>import com.fasterxml.jackson.databind.deser.std.StdDeserializer;<br><br>/**<br> * Jackson deserializer to automatically de-obfuscate fields <br> * annotated with @Obfuscated<br> */<br>public class UuidDeserializer extends StdDeserializer&lt;Object&gt; <br>        implements ContextualDeserializer {<br><br>    private static final long serialVersionUID = 1L;<br>    private final transient UuidConverterService converterService;<br><br>    @Autowired<br>    public UuidDeserializer(UuidConverterService converterService) {<br>        super(Object.class);<br>        this.converterService = converterService;<br>    }<br><br>    @Override<br>    public Object deserialize(JsonParser p, DeserializationContext ctxt) <br>            throws IOException {<br>        String obfuscatedValue = p.getText();<br><br>        if (obfuscatedValue == null || obfuscatedValue.isEmpty()) {<br>            return null;<br>        }<br><br>        UUID uuid = UUID.fromString(obfuscatedValue);<br>        return converterService.toOriginal(uuid);<br>    }<br><br>    @Override<br>    public JsonDeserializer&lt;?&gt; createContextual(DeserializationContext ctxt, <br>                                                BeanProperty property) {<br>        if (property != null) {<br>            Obfuscated annotation = property.getAnnotation(Obfuscated.class);<br>            if (annotation != null) {<br>                return new UuidDeserializer(converterService);<br>            }<br>        }<br>        return this;<br>    }<br>}</pre><h4>Step 5: Create Annotation Introspector</h4><p>Register the serializers/deserializers with Jackson:</p><pre>package com.example.api.security.obfuscation;<br><br>import com.fasterxml.jackson.databind.introspect.Annotated;<br>import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector;<br><br>/**<br> * Custom AnnotationIntrospector to detect @Obfuscated annotation <br> * and apply appropriate serializers/deserializers<br> */<br>public class ObfuscationAnnotationIntrospector <br>        extends NopAnnotationIntrospector {<br><br>    private static final long serialVersionUID = 1L;<br>    private final UuidSerializer serializer;<br>    private final UuidDeserializer deserializer;<br><br>    public ObfuscationAnnotationIntrospector(UuidSerializer serializer, <br>                                            UuidDeserializer deserializer) {<br>        this.serializer = serializer;<br>        this.deserializer = deserializer;<br>    }<br><br>    @Override<br>    public Object findSerializer(Annotated am) {<br>        Obfuscated annotation = am.getAnnotation(Obfuscated.class);<br>        if (annotation != null) {<br>            return serializer;<br>        }<br>        return null;<br>    }<br><br>    @Override<br>    public Object findDeserializer(Annotated am) {<br>        Obfuscated annotation = am.getAnnotation(Obfuscated.class);<br>        if (annotation != null) {<br>            return deserializer;<br>        }<br>        return null;<br>    }<br>}</pre><h4>Step 6: Create Argument Resolver for Controller Parameters</h4><p>Handle obfuscated path variables and request parameters:</p><pre>package com.example.api.security.obfuscation;<br><br>import java.util.Map;<br>import java.util.UUID;<br>import javax.servlet.http.HttpServletRequest;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.core.MethodParameter;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.bind.support.WebDataBinderFactory;<br>import org.springframework.web.context.request.NativeWebRequest;<br>import org.springframework.web.method.support.HandlerMethodArgumentResolver;<br>import org.springframework.web.method.support.ModelAndViewContainer;<br>import org.springframework.web.servlet.HandlerMapping;<br><br>/**<br> * Custom resolver for controller parameters annotated with @Obfuscated.<br> * <br> * Handles:<br> * - Retrieving value from path variables or request parameters<br> * - UUID format validation<br> * - De-obfuscation via UuidConverterService<br> * - Type conversion to target type (Long, Integer, String)<br> */<br>@Component<br>public class ObfuscatedArgumentResolver implements HandlerMethodArgumentResolver {<br><br>    private final UuidConverterService converterService;<br><br>    @Autowired<br>    public ObfuscatedArgumentResolver(UuidConverterService converterService) {<br>        this.converterService = converterService;<br>    }<br><br>    @Override<br>    public boolean supportsParameter(MethodParameter parameter) {<br>        return parameter.hasParameterAnnotation(Obfuscated.class);<br>    }<br><br>    @Override<br>    public Object resolveArgument(MethodParameter parameter, <br>                                 ModelAndViewContainer mavContainer,<br>                                 NativeWebRequest webRequest, <br>                                 WebDataBinderFactory binderFactory) <br>            throws Exception {<br><br>        HttpServletRequest request = <br>            webRequest.getNativeRequest(HttpServletRequest.class);<br>        String parameterName = parameter.getParameterName();<br><br>        // Try to get from path variables<br>        @SuppressWarnings(&quot;unchecked&quot;)<br>        Map&lt;String, String&gt; pathVariables = (Map&lt;String, String&gt;) <br>            request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);<br><br>        String uuidString = null;<br>        if (pathVariables != null &amp;&amp; pathVariables.containsKey(parameterName)) {<br>            uuidString = pathVariables.get(parameterName);<br>        }<br><br>        // If not found, try request parameters<br>        if (uuidString == null) {<br>            uuidString = webRequest.getParameter(parameterName);<br>        }<br><br>        // Return null if empty (let controller validation handle it)<br>        if (uuidString == null || uuidString.isEmpty()) {<br>            return null;<br>        }<br><br>        // Parse and validate UUID<br>        UUID uuid;<br>        try {<br>            uuid = UUID.fromString(uuidString);<br>        } catch (IllegalArgumentException e) {<br>            throw new IllegalArgumentException(<br>                &quot;Invalid UUID format for parameter &quot; + parameterName + <br>                &quot;: &quot; + uuidString, e<br>            );<br>        }<br><br>        // De-obfuscate to original value<br>        return converterService.toOriginal(uuid);<br>    }<br>}</pre><h4>Step 7: Register the Argument Resolver</h4><p>Create a bean post-processor to register the argument resolver:</p><pre>package com.example.api.security.obfuscation;<br><br>import java.util.ArrayList;<br>import java.util.List;<br>import org.springframework.beans.BeansException;<br>import org.springframework.beans.factory.config.BeanPostProcessor;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.method.support.HandlerMethodArgumentResolver;<br>import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;<br>import lombok.extern.slf4j.Slf4j;<br><br>/**<br> * Customizes RequestMappingHandlerAdapter to register <br> * ObfuscatedArgumentResolver at the head of the resolver list.<br> */<br>@Slf4j<br>@Component<br>public class RequestMappingHandlerAdapterCustomizer <br>        implements BeanPostProcessor {<br><br>    private final ObfuscatedArgumentResolver obfuscatedArgumentResolver;<br><br>    public RequestMappingHandlerAdapterCustomizer(<br>            ObfuscatedArgumentResolver resolver) {<br>        this.obfuscatedArgumentResolver = resolver;<br>    }<br><br>    @Override<br>    public Object postProcessAfterInitialization(Object bean, String beanName) <br>            throws BeansException {<br>        <br>        if (bean instanceof RequestMappingHandlerAdapter) {<br>            RequestMappingHandlerAdapter adapter = <br>                (RequestMappingHandlerAdapter) bean;<br><br>            List&lt;HandlerMethodArgumentResolver&gt; existingResolvers = <br>                adapter.getArgumentResolvers();<br><br>            if (existingResolvers != null) {<br>                // Check if already registered<br>                boolean alreadyRegistered = existingResolvers.stream()<br>                    .anyMatch(r -&gt; r instanceof ObfuscatedArgumentResolver);<br><br>                if (alreadyRegistered) {<br>                    log.warn(&quot;ObfuscatedArgumentResolver already registered&quot;);<br>                    return bean;<br>                }<br><br>                // Add our resolver at the beginning<br>                List&lt;HandlerMethodArgumentResolver&gt; newResolvers = <br>                    new ArrayList&lt;&gt;();<br>                newResolvers.add(obfuscatedArgumentResolver);<br>                newResolvers.addAll(existingResolvers);<br>                <br>                adapter.setArgumentResolvers(newResolvers);<br>            }<br>        }<br>        return bean;<br>    }<br>}</pre><h4>Step 8: Configure Spring Beans</h4><p>Configure the obfuscation components in your Spring configuration:</p><pre>&lt;!-- Spring XML Configuration --&gt;<br>&lt;beans&gt;<br>    &lt;!-- Jackson ObjectMapper configuration --&gt;<br>    &lt;bean id=&quot;objectMapper&quot; <br>          class=&quot;org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean&quot;&gt;<br>        &lt;property name=&quot;annotationIntrospector&quot;&gt;<br>            &lt;bean class=&quot;com.example.api.security.obfuscation.ObfuscationAnnotationIntrospector&quot;&gt;<br>                &lt;constructor-arg ref=&quot;obfuscationSerializer&quot; /&gt;<br>                &lt;constructor-arg ref=&quot;obfuscationDeserializer&quot; /&gt;<br>            &lt;/bean&gt;<br>        &lt;/property&gt;<br>    &lt;/bean&gt;<br><br>    &lt;!-- Serializer for obfuscation --&gt;<br>    &lt;bean id=&quot;obfuscationSerializer&quot; <br>          class=&quot;com.example.api.security.obfuscation.UuidSerializer&quot;&gt;<br>        &lt;constructor-arg ref=&quot;uuidConverterService&quot; /&gt;<br>    &lt;/bean&gt;<br><br>    &lt;!-- Deserializer for obfuscation --&gt;<br>    &lt;bean id=&quot;obfuscationDeserializer&quot; <br>          class=&quot;com.example.api.security.obfuscation.UuidDeserializer&quot;&gt;<br>        &lt;constructor-arg ref=&quot;uuidConverterService&quot; /&gt;<br>    &lt;/bean&gt;<br>&lt;/beans&gt;</pre><p>Or using Java configuration:</p><pre>package com.example.api.config;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;<br>import com.example.api.security.obfuscation.*;<br>import com.fasterxml.jackson.databind.ObjectMapper;<br><br>@Configuration<br>public class ObfuscationConfig {<br><br>    @Bean<br>    public UuidConverterService uuidConverterService() {<br>        return new UuidConverterService();<br>    }<br><br>    @Bean<br>    public UuidSerializer uuidSerializer(UuidConverterService service) {<br>        return new UuidSerializer(service);<br>    }<br><br>    @Bean<br>    public UuidDeserializer uuidDeserializer(UuidConverterService service) {<br>        return new UuidDeserializer(service);<br>    }<br><br>    @Bean<br>    public ObfuscationAnnotationIntrospector obfuscationIntrospector(<br>            UuidSerializer serializer, UuidDeserializer deserializer) {<br>        return new ObfuscationAnnotationIntrospector(serializer, deserializer);<br>    }<br><br>    @Bean<br>    public ObjectMapper objectMapper(<br>            ObfuscationAnnotationIntrospector introspector) {<br>        return Jackson2ObjectMapperBuilder.json()<br>            .annotationIntrospector(introspector)<br>            .build();<br>    }<br>}</pre><h3>Usage Examples</h3><h4>Example 1: DTO with Obfuscated Fields</h4><pre>package com.example.api.dto;<br><br>import com.example.api.security.obfuscation.Obfuscated;<br>import lombok.Data;<br><br>@Data<br>public class ProductResponseDto {<br>    @Obfuscated<br>    private Long id;  // Will be serialized as UUID<br>    <br>    private String name;<br>    private Double price;<br>    <br>    @Obfuscated<br>    private Long categoryId;  // Will be serialized as UUID<br>}</pre><p><strong>JSON Output:</strong></p><pre>{<br>  &quot;id&quot;: &quot;01000000-0000-0000-0000-00000000007b&quot;,<br>  &quot;name&quot;: &quot;Laptop&quot;,<br>  &quot;price&quot;: 999.99,<br>  &quot;categoryId&quot;: &quot;01000000-0000-0000-0000-000000000015&quot;<br>}</pre><h3>Example 2: Controller with Obfuscated Parameters</h3><pre>package com.example.api.controller;<br><br>import com.example.api.dto.ProductResponseDto;<br>import com.example.api.security.obfuscation.Obfuscated;<br>import org.springframework.web.bind.annotation.*;<br>import javax.validation.constraints.NotNull;<br><br>@RestController<br>@RequestMapping(&quot;/api/products&quot;)<br>public class ProductController {<br><br>    @GetMapping(&quot;/{productId}&quot;)<br>    public ProductResponseDto getProduct(<br>            @PathVariable(&quot;productId&quot;) @Obfuscated @NotNull Long productId) {<br>        // productId is automatically converted from UUID to Long<br>        return productService.findById(productId);<br>    }<br><br>    @GetMapping(&quot;/category/{categoryId}&quot;)<br>    public List&lt;ProductResponseDto&gt; getProductsByCategory(<br>            @PathVariable(&quot;categoryId&quot;) @Obfuscated @NotNull Long categoryId) {<br>        return productService.findByCategory(categoryId);<br>    }<br>}</pre><p><strong>Example API Call:</strong></p><pre>GET /api/products/01000000-0000-0000-0000-00000000007b</pre><h3>Testing</h3><h4>Unit Test Example</h4><pre>package com.example.api.security.obfuscation;<br><br>import org.junit.jupiter.api.Test;<br>import org.junit.jupiter.api.BeforeEach;<br>import java.util.UUID;<br>import static org.junit.jupiter.api.Assertions.*;<br><br>class UuidConverterServiceTest {<br><br>    private UuidConverterService service;<br><br>    @BeforeEach<br>    void setUp() {<br>        service = new UuidConverterService();<br>    }<br><br>    @Test<br>    void testLongConversionAndBack() {<br>        Long originalId = 123456789L;<br>        UUID uuid = service.toUuid(originalId);<br>        <br>        assertNotNull(uuid);<br>        <br>        Long retrievedId = service.toLong(uuid);<br>        assertEquals(originalId, retrievedId);<br>    }<br><br>    @Test<br>    void testIntegerConversion() {<br>        Integer originalId = 987654;<br>        UUID uuid = service.toUuid(originalId);<br>        Integer retrievedId = service.toInteger(uuid);<br>        <br>        assertEquals(originalId, retrievedId);<br>    }<br><br>    @Test<br>    void testStringConversion() {<br>        String originalId = &quot;user123&quot;;<br>        UUID uuid = service.toUuid(originalId);<br>        String retrievedId = service.toString(uuid);<br>        <br>        assertEquals(originalId, retrievedId);<br>    }<br><br>    @Test<br>    void testDeterministicConversion() {<br>        Long id = 42L;<br>        UUID uuid1 = service.toUuid(id);<br>        UUID uuid2 = service.toUuid(id);<br>        <br>        assertEquals(uuid1, uuid2, <br>            &quot;Same ID should produce same UUID&quot;);<br>    }<br><br>    @Test<br>    void testNullHandling() {<br>        assertNull(service.toUuid((Long) null));<br>        assertNull(service.toLong(null));<br>    }<br><br>    @Test<br>    void testStringTooLong() {<br>        String tooLong = &quot;1234567890123456&quot;; // 16 characters<br>        <br>        assertThrows(IllegalArgumentException.class, () -&gt; {<br>            service.toUuid(tooLong);<br>        });<br>    }<br><br>    @Test<br>    void testTypeDetection() {<br>        UUID longUuid = service.toUuid(100L);<br>        UUID intUuid = service.toUuid(200);<br>        UUID strUuid = service.toUuid(&quot;abc&quot;);<br><br>        assertEquals(Long.class, service.detectType(longUuid));<br>        assertEquals(Integer.class, service.detectType(intUuid));<br>        assertEquals(String.class, service.detectType(strUuid));<br>    }<br>}</pre><h3>Best Practices</h3><ul><li><strong>Use Consistently</strong>: Apply @Obfuscated to all technical IDs in your API</li><li><strong>Document the Format</strong>: Inform API consumers about the UUID format</li><li><strong>Validate Input</strong>: Always validate UUID format in controllers</li><li><strong>Handle Errors Gracefully</strong>: Provide clear error messages for invalid UUIDs</li><li><strong>Consider Performance</strong>: The conversion is lightweight but cache frequently accessed conversions if needed</li><li><strong>Security Considerations</strong>: This obfuscates but doesn’t encrypt — don’t rely on it for authentication</li></ul><h3>Advantages</h3><ul><li>✅ <strong>Automatic</strong>: Works seamlessly with Jackson serialization/deserialization</li><li>✅ <strong>Type-Safe</strong>: Maintains original data types internally</li><li>✅ <strong>Deterministic</strong>: Same ID always produces same UUID</li><li>✅ <strong>Reversible</strong>: Full bidirectional conversion</li><li>✅ <strong>Flexible</strong>: Supports Long, Integer, and String IDs</li><li>✅ <strong>Transparent</strong>: Controllers work with original types</li></ul><h3>Limitations</h3><ul><li>⚠️ String IDs limited to 15 UTF-8 bytes</li><li>⚠️ Only supports Long, Integer, and String types</li><li>⚠️ Not cryptographically secure (predictable mapping)</li><li>⚠️ Requires custom serialization configuration</li></ul><h3>Conclusion</h3><p>This comprehensive obfuscation solution provides a robust way to hide internal IDs in your REST API while maintaining full type safety and automatic conversion. By leveraging Spring Boot’s extensibility and Jackson’s customization features, we create a seamless developer experience that enhances API security without adding complexity to controller code.</p><p>The deterministic nature of the conversion ensures consistency across requests while the annotation-driven approach keeps the implementation clean and maintainable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d6e7b28fa5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OWASP A02:2021 — Cryptographic Failures]]></title>
            <link>https://medium.com/@anassguendef/owasp-a02-2021-cryptographic-failures-0ba0bec61f37?source=rss-2f0c7102fced------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ba0bec61f37</guid>
            <category><![CDATA[cryptology]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[owasp-top-10]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Anass Guendef]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 12:24:04 GMT</pubDate>
            <atom:updated>2025-03-12T12:24:04.864Z</atom:updated>
            <content:encoded><![CDATA[<h3>OWASP A02:2021 — Cryptographic Failures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LapLSXHPb5jVyNiPSmMIMA.png" /></figure><p>According to OWASP Top 10:2021, Cryptographic Failures ranks #2, with 79% of tested applications showing vulnerabilities in this category. This article explains the common causes of these failures and provides guidance on addressing them.</p><h3>What are Cryptographic Failures?</h3><p>Cryptographic failures occur when applications implement weak or broken cryptographic algorithms, use hard-coded passwords, or lack proper cryptographic protection. These vulnerabilities can lead to sensitive data exposure. Common attack vectors include collision attacks, brute force attacks, and bit-flipping attacks.</p><h3>Understanding Common Attacks</h3><h3>1. Collision Attacks</h3><p>Collision attacks exploit weaknesses in hash functions where different inputs produce the same hash value. Here’s an example demonstrating a vulnerable session management implementation:</p><pre>public class Session {<br>    private final String username;<br><br>    public Session(String username) {<br>        this.username = username;<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        // WARNING: This is a weak implementation for demonstration purposes<br>        int hash = 0;<br>        for (char c : username.toCharArray()) {<br>            hash ^= (int) c;<br>        }<br>        return hash % 7;<br>    }<br><br>    @Override<br>    public boolean equals(Object obj) {<br>        if (this == obj) return true;<br>        if (obj == null || getClass() != obj.getClass()) return false;<br>        Session session = (Session) obj;<br>        return username.equals(session.username);<br>    }<br>}</pre><p>This implementation has several critical flaws:</p><ul><li>Limited output range (only 7 possible values)</li><li>Poor distribution due to simple XOR operations</li><li>Predictable patterns for similar usernames (“abc” and “cba”)</li><li>Lack of cryptographic security</li></ul><p>The impact includes:</p><ul><li>Performance degradation from O(1) to O(n) for HashMap operations</li><li>Vulnerability to DoS attacks through deliberate hash collisions</li><li>Potential session confusion</li></ul><p><strong>Best Practice:</strong> Use cryptographically secure hash functions like SHA-256 or SHA-3 for session tokens and security-critical operations.</p><h3>2. Brute Force Attacks</h3><p>Brute force attacks systematically attempt to guess passwords using predefined dictionaries of commonly used or leaked passwords. These attacks succeed when applications have:</p><ul><li>Weak password policies</li><li>No limit on login attempts</li><li>Lack of account lockout mechanisms</li><li>Absence of multi-factor authentication (MFA)</li></ul><h3>Real-Life Examples</h3><ol><li>Zoom (2020): Credential stuffing attacks led to unauthorized access of meetings and personal data</li><li>Disney+ (2019): Large-scale credential stuffing affected thousands of accounts</li><li>LinkedIn and MyFitnessPal: Leaked credentials were used in subsequent attacks on other services</li></ol><h3>Mitigation Strategies</h3><ul><li>Implement strong password policies</li><li>Enable passwordless authentication options</li><li>Apply rate limiting and IP-based restrictions</li><li>Monitor for suspicious login patterns</li><li>Integrate with breach detection services (e.g., Have I Been Pwned)</li><li>Implement CAPTCHA and MFA</li></ul><h3>3. Bit-Flipping Attacks</h3><p>Bit-flipping attacks manipulate encrypted data by modifying specific bits, typically exploiting vulnerabilities in block ciphers operating in CBC (Cipher Block Chaining) mode without integrity checks. Here’s a demonstration:</p><pre>public class BitFlippingAttackDemo {<br>    public static void main(String[] args) throws Exception {<br>        String plaintext = &quot;admin=0&quot;;<br>        <br>        // Generate key and IV<br>        SecretKey key = KeyGenerator.getInstance(&quot;AES&quot;).generateKey();<br>        byte[] iv = new byte[16];<br>        <br>        // Encrypt original data<br>        byte[] ciphertext = encrypt(plaintext.getBytes(), key, iv);<br>        <br>        // Modify IV to affect decryption<br>        byte[] modifiedIv = iv.clone();<br>        modifiedIv[6] = 1;<br>        <br>        // Demonstrate the attack<br>        byte[] decryptedModified = decrypt(ciphertext, key, modifiedIv);<br>        // Result: &quot;admin=1&quot; (unauthorized elevation)<br>    }<br>}</pre><h3>Real-World Implications</h3><ul><li>Token tampering in authentication systems</li><li>Unauthorized privilege escalation</li><li>Padding oracle attacks in CBC mode encryption</li></ul><h3>Mitigation Strategies</h3><ol><li>Use authenticated encryption (AEAD modes like GCM)</li><li>Implement message authentication codes (HMAC)</li><li>Validate data integrity before processing</li><li>Apply proper key management practices</li></ol><h3>Best Practices for Preventing Cryptographic Failures</h3><ol><li>Strong Algorithm Selection Use modern, standardized encryption algorithms Avoid deprecated algorithms (MD5, SHA-1, DES) Implement proper key sizes and initialization vectors</li><li>Secure Implementation Use validated cryptographic libraries Implement secure key management Apply proper padding and modes of operation</li><li>Data Protection Encrypt sensitive data at rest and in transit Implement proper access controls Regular security audits and updates</li><li>Authentication Security Implement MFA where possible Use secure session management Apply rate limiting and monitoring</li></ol><h3>Appendix</h3><p><strong>Initialization Vector (IV) :</strong> An IV is a random value used to ensure that encrypting the same plaintext multiple times produces different ciphertexts.</p><p><strong>Have I Been Pwned (HIBP) :</strong> HIBP is a service that:</p><ul><li>Maintains a database of compromised credentials from known data breaches</li><li>Allows checking if emails/passwords appear in breaches</li><li>Provides API integration for real-time password checks</li></ul><p><strong>CBC (Cipher Block Chaining) Mode :</strong> CBC is an encryption mode where:</p><ul><li>Each plaintext block is XORed with the previous ciphertext block before encryption</li><li>The first block uses an IV instead of a previous ciphertext</li><li>Changes in one block affect all subsequent blocks</li></ul><p>Vulnerabilities:</p><ul><li>No integrity checking (can be modified without detection)</li><li>Susceptible to padding oracle attacks</li><li>Requires padding to handle incomplete blocks</li></ul><p><strong>Token Tampering :</strong> This involves modifying authentication/session tokens to:</p><ul><li>Escalate privileges (changing “role=user” to “role=admin”)</li><li>Impersonate other users</li><li>Bypass security controls</li></ul><p><strong>Padding Oracle Attacks :</strong> These attacks exploit CBC mode’s padding validation to:</p><ul><li>Decrypt ciphertext without knowing the key</li><li>Work by observing error messages about invalid padding</li><li>Can be automated to decrypt entire messages</li></ul><p><strong>AEAD (Authenticated Encryption with Associated Data) Modes like GCM :</strong> GCM (Galois/Counter Mode) provides:</p><ul><li>Encryption for confidentiality</li><li>Built-in authentication</li><li>Optional associated data authentication</li></ul><p>Benefits of GCM over CBC:</p><ul><li>Detects any modifications to ciphertext</li><li>No padding required</li><li>Parallel processing capability</li><li>Protection against bit-flipping attacks</li><li>Built-in authentication eliminates need for separate HMAC</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ba0bec61f37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSL — Mutual authentication (Part 1)]]></title>
            <link>https://medium.com/@anassguendef/ssl-mutual-authentication-part-1-76534505fcb4?source=rss-2f0c7102fced------2</link>
            <guid isPermaLink="false">https://medium.com/p/76534505fcb4</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Anass Guendef]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 12:16:00 GMT</pubDate>
            <atom:updated>2025-03-12T12:16:00.009Z</atom:updated>
            <content:encoded><![CDATA[<h3>SSL — Mutual authentication (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHPU3cVh1Pi74GRXvKQeag.png" /></figure><p>SSL Mutual authentication refers to two applications authenticating each other at the same time using the security SSl (Secure Sockets Layer) Protocol. In most cases, we use a keystore and a truststore when our application needs to communicate over SSL/TLS. So, let first define the keystore and the truststore.</p><h3>What are Keystore and Trustore used for ?</h3><p>Keystore and truststore are password-protected files that are used to store certificates and private keys. The default format of these files until Java 8 is JKS. From Java 9 and above, the default format is PKCS12. This new format is a standard and language-independent, whereas JKS is a Java-specific format.</p><h3>Differences between Keystore and Truststore</h3><p>Keystore :</p><ul><li>Contains private keys and identity certificates</li><li>Used to prove the identity of the application</li><li>Should be kept strictly confidential</li><li>Used when the application acts as a server</li><li>Default password: “changeit”</li><li>Default location: $JAVA_HOME/lib/security/cacerts</li></ul><p>Truststore :</p><ul><li>Contains certificates from other parties</li><li>Used to verify the identity of the other party</li><li>Can be shared publicly</li><li>Used when the application acts as a client</li><li>Contains certificates of trusted Certificate Authorities (CAs)</li></ul><h3>How Mutual Authentication Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eB-OFaXAsLj6uCwbfM1-Q.jpeg" /></figure><p>As represented in this schema above, the mutual SSL authentication follows these steps:</p><ol><li>The client initiates the connection and sends supported cipher suites to the server</li><li>The server responds by selecting a cipher suite and sending its certificate from its keystore</li><li>The client verifies the server’s certificate using its local truststore. If the certificate is not trusted, an SSLHandshakeException is thrown</li><li>If verification succeeds, the client sends its certificate from its keystore to the server</li><li>The server verifies the client’s certificate using its local truststore</li><li>If all verifications succeed, both parties establish encrypted communication</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76534505fcb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concrétiser vos projets personnels]]></title>
            <link>https://medium.com/@anassguendef/concr%C3%A9tiser-vos-projets-personnels-4b1f0a45c390?source=rss-2f0c7102fced------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b1f0a45c390</guid>
            <category><![CDATA[management]]></category>
            <category><![CDATA[leadership-skills]]></category>
            <category><![CDATA[suivi]]></category>
            <category><![CDATA[gestion-de-projet]]></category>
            <category><![CDATA[développement-personnel]]></category>
            <dc:creator><![CDATA[Anass Guendef]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 13:52:27 GMT</pubDate>
            <atom:updated>2024-12-05T13:52:27.648Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sU9meQ86MT-KaMN1avwUGQ.png" /></figure><p>L’année 2024 est bientôt écoulée. En cette période de l’année, il est important de prendre un petit moment avec soi-même pour réfléchir aux objectifs de l’année prochaine.</p><p>Dans cet article destiné au grand public, je vais vous expliquer ma démarche pour définir mes objectifs personnels et suivre leur avancement. En bonus, je peux vous envoyer un fichier Excel modèle que j’utilise comme support pour définir et suivre mes objectifs. Demandez le en commentaire 💬, mettez votre e-mail ✉️.</p><h3>Calculer la capacité de production</h3><p>La première chose à définir est sans doute vos disponibilités. Répondez simplement à ces questions :</p><ol><li><em>Combien d’heures suis-je capable de consacrer chaque jour de la semaine à mes projets personnels ?</em></li><li><em>Quels sont mes jours de repos?</em></li></ol><p>À partir de ces deux informations, vous pouvez calculer votre capacité de production en heures sur une année. Vous pouvez également calculer votre capacité de production restante. Sur mon support Excel, j’ai mis en œuvre une macro qui calcule automatiquement ces deux informations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYddCkkRmRdRWAAGqpGtYA.png" /></figure><h3>Définir un Objectif SMART</h3><p>Définir un objectif n’est pas toujours facile. Par nature, nous avons tendance à vouloir toucher les étoiles et accomplir les 12 travaux d’Hercule. Afin de cadrer cette ambition, j’utilise la méthode SMART pour définir mes projets. Je vous explique directement avec un exemple :</p><p>Imaginons que je suis de nature sédentaire, je ne le suis pas en réalité 😉, et que je veux changer cela. Je pourrais exprimer mon intention comme suit :</p><blockquote><em>Améliorer ma condition physique : retrouver une meilleure forme physique et plus d’énergie.</em></blockquote><p>Voyons si cet objectif est SMART ou pas du tout.</p><ul><li>S pour SPÉCIFIQUE <em>(Qui ? Quoi ? Pourquoi ? Où ? Quand ?)</em> : Pratiquer la course à pied régulièrement.</li><li>M pour MESURABLE <em>(Combien ? À quelle fréquence ?)</em> : Courir 5 km sans pause.</li><li>A pour ATTEIGNABLE <em>(Faisable ?)</em> : Commencer par des sessions de 15 minutes et augmenter progressivement.</li><li>R pour RELEVANT <em>(Pertinent — est-ce crucial pour ce que vous souhaitez finalement atteindre ?)</em> : Améliorer la santé et le bien-être général.</li><li>T pour TIME-BOUND <em>(Basé sur le temps — Quand ?)</em> : 30/04/2025.</li></ul><p>La méthode SMART nous permet de bien définir le périmètre de l’objectif et de confirmer sa pertinence ou non.</p><h3>Définir un Projet CLEAR</h3><p>Afin de concrétiser un objectif, l’étape suivante est de définir un projet, ou plusieurs. Là aussi, il y a une méthode intéressante pour cadrer votre définition de projet. Vous allez la découvrir sans tarder avec un exemple :</p><blockquote><em>Projet : Du canapé aux 5 km</em></blockquote><ul><li>C pour COLLABORATIF <em>(Ai-je impliqué toutes les parties prenantes nécessaires dans la planification et l’exécution du projet ?)</em> : Rejoindre un club de course à pied local ou trouver un partenaire d’entraînement.</li><li>L pour LIMITÉ <em>(Ai-je défini clairement les délais et les ressources nécessaires pour le projet ?)</em> : Sessions de 30–45 minutes, 3 fois par semaine.</li><li>E pour ÉVOLUTIF <em>(Ai-je prévu des étapes intermédiaires pour suivre la progression du projet ?)</em> : Prévoir des étapes intermédiaires pour suivre la progression, comme augmenter progressivement la distance chaque semaine.</li><li>A pour ATTEIGNABLE <em>(Le projet est-il réaliste compte tenu des ressources et des contraintes ?)</em> : Commencer par une alternance marche/course avec des paliers progressifs.</li><li>R pour RÉCOMPENSANT <em>(Quels sont les bénéfices attendus du projet et comment la réussite sera-t-elle reconnue ?)</em> : Célébrer chaque kilomètre gagné et s’offrir des équipements sportifs.</li></ul><h3>Décomposer votre projet en tâches SMALL</h3><p>Dans cette étape, on scinde notre projet en un ensemble de tâches si petites qu’il devient certain de les réussir.</p><ul><li>S pour SIMPLE : “Bilan de santé initial”, une tâche compréhensible, sans complexité inutile dans la définition.</li><li>M pour MESURABLE : “Certificat médical d’aptitude”. Comme dans la méthode SMART, chaque tâche doit avoir un indicateur clair de succès.</li><li>A pour ACTIONNABLE : Les tâches doivent être concrètes et orientées vers l’action. Elles doivent répondre à la question : Que dois-je faire exactement ?</li><li>L pour LIMITÉE : “Le temps estimé est de 2 heures”, avec des contraintes claires en termes de temps ou de ressources.</li><li>L pour LIÉE : Connectée à l’objectif global, par exemple : “Améliorer ma condition physique”.</li></ul><h3>Suivi régulier des projets</h3><p>Une fois que vous avez défini vos projets, il ne reste plus qu’à passer à l’action :</p><ol><li>Bloquez un temps de travail personnel sur votre agenda numérique préféré (Google Agenda, par exemple) en créant des événements récurrents selon les disponibilités définies lors de la première étape.</li><li>Créez des listes de tâches et affectez-les progressivement en fonction de leur priorité (vous pouvez utiliser Google Tasks, par exemple).</li><li>Exécutez une tâche à la fois, en vous concentrant pleinement sur chacune pour plus d’efficacité.</li><li>Réservez un créneau mensuel pour consolider votre avancement et définir des actions afin de rester sur la bonne voie.</li><li>Suivez votre progression : Sur mon support Excel, chaque projet dispose d’une feuille dédiée pour suivre son avancement, et un tableau consolidé regroupe tous mes projets pour offrir une vue d’ensemble sur ma progression globale.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0itewRE3W-eGTMPuOvuNlQ.png" /></figure><h3>Aide visuelle</h3><p>Pour mieux visualiser votre travail, vous pouvez utiliser plusieurs types de graphiques :</p><ol><li><strong>Graphique de progression par projet</strong> : Montrez le pourcentage d’avancement de chaque projet.</li><li><strong>Graphique de charge de travail</strong> : Comparez les estimations initiales et la réalité pour chaque projet.</li><li><strong>Suivi des reports</strong> : Identifiez les projets ayant le plus de reports en affichant le temps estimé initial par rapport au temps reporté.</li><li><strong>Distribution du reste à faire par projet</strong> : Visualisez rapidement quel projet nécessite le plus d’investissement.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpeVvEGCG-cj9mMKvx08ag.png" /></figure><p>La cerise 🍒 sur le gâteau : Un thermomètre 🌡️ qui affiche l’avancement global de tous vos projets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*0D2m0B0h1SsJqpru7ALy4w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b1f0a45c390" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OWASP A01:2021 — Broken Access Control Attack Scenarios]]></title>
            <link>https://medium.com/@anassguendef/owasp-a01-2021-broken-access-control-attack-scenarios-9ce65f51301e?source=rss-2f0c7102fced------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ce65f51301e</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[owasp-top-10]]></category>
            <dc:creator><![CDATA[Anass Guendef]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 13:11:31 GMT</pubDate>
            <atom:updated>2024-11-18T13:11:31.248Z</atom:updated>
            <content:encoded><![CDATA[<h3>OWASP A01:2021 — Broken Access Control Attack Scenarios</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AW4Ri7vo_1_6YKx2MyB5iw.jpeg" /></figure><p>Broken Access Control is the #1 risk according to OWASP Top 10 2021, with 94% of tested applications affected. What is this attack? What are its common scenarios? And how can we prevent them?</p><h3>What is Broken Access Control?</h3><p>Access Control defines the authorizations allowed for users to access resources. Poor access control may lead to accessing unauthorized information, modifying or deleting data.</p><h3>Access Control vulnerabilities</h3><h4>Violation of privilege</h4><p>This occurs when an authenticated regular user modifies the URL or parameters to access unauthorized resources:</p><pre>// Original user URL<br>GET /api/user/profile/123<br>// Modified to access admin panel<br>GET /api/admin/users</pre><p>To prevent this attack:</p><ol><li>Implement proper role-based authentication for all routes</li><li>Implement audit logging for all privileged operations</li><li>Use principle of least privilege</li><li>Regularly review and update role assignments</li></ol><h4>Parameter Manipulation</h4><p>This occurs when a user modifies request parameters to access another user’s information:</p><pre>// Original request<br>GET /api/account?user_id=123<br>// Modified request<br>GET /api/account?user_id=456</pre><p>Prevention strategies:</p><ol><li>Implement Resource ownership middleware</li><li>Use UUID instead of sequential IDs</li><li>Implement rate limiting</li><li>Validate all input parameters</li></ol><h4>Insecure Direct Object References (IDOR)</h4><p>This occurs when a user manipulates a resource identifier to access unauthorized information:</p><pre>// Original request to view own invoice<br>GET /api/invoices/12345<br>// Modified to access another user&#39;s invoice<br>GET /api/invoices/12346</pre><p>Prevention strategies:</p><ol><li>Implement ownership checks</li><li>Implement context-based access control</li><li>Use indirect reference maps (real IDs are not exposed to users)</li></ol><h4>JWT Token Manipulation</h4><p>This attack involves a user sending a modified JWT token to bypass authentication or escalate privileges:</p><pre>// Original JWT payload<br>{<br> &quot;user_id&quot;: 123,<br> &quot;role&quot;: &quot;user&quot;,<br> &quot;exp&quot;: 1735689600<br>}<br>// Modified JWT payload<br>{<br> &quot;user_id&quot;: 123,<br> &quot;role&quot;: &quot;admin&quot;,<br> &quot;exp&quot;: 1735689600<br>}</pre><p>Prevention strategies:</p><ol><li>Use asymmetric signing</li><li>Generate tokens with minimal payload</li><li>Generate unique token IDs</li><li>Use short expiration times</li><li>Implement regular key rotation</li><li>Implement token blacklisting</li></ol><h4>Missing Access Control Checks</h4><p>This occurs when an API fails to verify authentication before providing access:</p><pre>// Vulnerable API endpoint<br>app.get(&#39;/api/user/data&#39;, (req, res) =&gt; {<br> // No authentication check<br> return res.json(userData);<br>});<br>// Secure implementation<br>app.get(&#39;/api/user/data&#39;, authenticateUser, (req, res) =&gt; {<br> if (!req.user.hasPermission(&#39;read_data&#39;)) {<br> return res.status(403).json({ error: &#39;Unauthorized&#39; });<br> }<br> return res.json(userData);<br>});</pre><p>Prevention strategy:</p><p>Implement proper Access Control middleware</p><h4>Force Browsing</h4><p>This occurs when an attacker guesses URLs:</p><pre>// Attempting to access hidden admin pages<br>GET /admin/dashboard<br>GET /admin/users<br>GET /admin/settings</pre><p>Prevention strategies:</p><ol><li>Implement URL pattern validation middleware</li><li>Implement static resource protection</li><li>Implement proper error handling</li><li>Use security headers (X-Frame-Options, Content-Security-Policy)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ce65f51301e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Postgres Sql Plan]]></title>
            <link>https://medium.com/@anassguendef/understanding-postgres-sql-plan-310799b30c4e?source=rss-2f0c7102fced------2</link>
            <guid isPermaLink="false">https://medium.com/p/310799b30c4e</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-performance-tuning]]></category>
            <category><![CDATA[sql-optimization]]></category>
            <category><![CDATA[sql-performance]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Anass Guendef]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 14:21:27 GMT</pubDate>
            <atom:updated>2024-11-20T09:02:09.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APHwpcdLoknUaVWdm4Jakg.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>Understanding SQL plan is mandatory if we are aiming to optimize an SQL query. The plan provides us with some interesting information that we are going to explore together in this article.</p><h3>Situation</h3><p>Consider that we have a table salary_adjustments defined like this:</p><pre>-- Create table<br>CREATE TABLE salary_adjustments (<br>    adjustment_id INTEGER PRIMARY KEY,    <br>    employee_id INTEGER,                  <br>    previous_salary_id INTEGER,           <br>    amount DECIMAL(10,2),<br>    effective_date DATE<br>);<br><br>-- Create index on employee_id<br>CREATE INDEX idx_salary_adj_emp <br>ON salary_adjustments(employee_id);</pre><p>Which of those is the most performant query?</p><pre>SELECT <br>    sa.employee_id as emp,<br>    COUNT(sa.adjustment_id) as salary_adjustment_count<br>FROM salary_adjustments sa<br>GROUP BY sa.employee_id<br>HAVING COUNT(sa.adjustment_id) &gt; 1;</pre><pre>SELECT <br>    sa.employee_id as emp,<br>    COUNT(*) as salary_adjustment_count<br>FROM salary_adjustments sa<br>GROUP BY sa.employee_id<br>HAVING COUNT(*) &gt; 1;</pre><p>To answer this, let’s examine the query plan.</p><h3>Execution Plan</h3><p>To run an execution plan you can execute one of these commands:</p><p><strong>EXPLAIN:</strong></p><ul><li>To quickly see how PostgreSQL plans to execute the query</li><li>To verify index usage</li><li>When you don’t want to impact the database (heavy query)</li></ul><p><strong>EXPLAIN ANALYZE:</strong></p><ul><li>To see actual performance metrics</li><li>To identify estimation discrepancies</li><li>For performance debugging</li><li>To measure optimization impact</li><li>Actually executes the query, while EXPLAIN only shows the plan</li></ul><h3>Comparing the executions plan of our queries</h3><p>Version with COUNT(adjustment_id) :</p><pre>GroupAggregate  (cost=140239785.58..193956412.94 rows=158293619 width=16) (actual time=334528.646..411045.462 rows=134377 loops=1)<br>  Group Key: employee_id<br>  Filter: (count(adjustment_id) &gt; 1)<br>  Rows Removed by Filter: 503475932<br>  -&gt;  Sort  (cost=140239785.58..141500120.46 rows=504133952 width=16) (actual time=281905.337..333116.802 rows=504035748 loops=1)<br>        Sort Key: employee_id<br>        Sort Method: external merge  Disk: 12824480kB<br>        -&gt;  Seq Scan on salary_adjustments sa  (cost=0.00..62076736.20 rows=504133952 width=16) (actual time=0.011..112818.425 rows=504035748 loops=1)<br><br>Planning Time: 0.092 ms<br>Execution Time: 413822.092 ms</pre><p>Version with COUNT(*) :</p><pre>GroupAggregate  (cost=0.57..109723958.14 rows=163294901 width=16) (actual time=86675.662..206504.852 rows=134377 loops=1)<br>  Group Key: employee_id<br>  Filter: (count(*) &gt; 1)<br>  Rows Removed by Filter: 503475932<br>  -&gt;  Index Only Scan using idx_salary_adj_emp on salary_adjustments sa  (cost=0.57..55712632.70 rows=506419104 width=8) (actual time=0.101..118494.131 rows=506246363 loops=1)<br>        Heap Fetches: 788294<br><br>Planning Time: 1.882 ms<br>Execution Time: 206511.080 ms</pre><p>According to the execution plans, we can clearly answer the question: the version with COUNT(*) is more performant. It took half the time of the version with COUNT(adjustment_id), but why?</p><p>As we can see, in the version with COUNT(*), the Executor performed an <em>Index Only Scan</em> while it performed a <em>Seq Scan</em> with an <em>external sort</em> that used about 12.8 GB of disk in the other version.</p><p>The version with COUNT(*) needs to access only the index because the index on employee_id contains all the information we need to perform our operations — we’re just counting rows per employee_id. Whereas, in the version with COUNT(adjustment_id), we need to access both employee_id and adjustment_id columns, and we don’t have an index that contains both of them. This forces PostgreSQL to read the entire table (Seq Scan) and sort the data to perform the grouping operation.</p><h3>Different types of Scan</h3><p>There are several types of scans, let’s explain three of them:</p><p><strong>Seq Scan</strong>: performs as if you have a book and you read it page by page sequentially.</p><p><strong>Index Scan</strong>: performs as if you look into the index to see which chapter interests you more, then you look at the corresponding page.</p><p><strong>Index Only Scan</strong>: performs as if you look only into the index to find information that does not need to see other pages, such as getting the numbers of chapters in the book.</p><h3>Going deeper in the explanation</h3><h4>Reading an execution plan</h4><p>An execution plan should be read bottom-top:</p><ul><li>Version with COUNT(<em>): Index Only Scan with Heap Fetches -&gt; GroupAggregate and Filter (count(</em>) &gt; 1)</li><li>Version with COUNT(adjustment_id): Seq Scan -&gt; Sort with external merge Disk -&gt; GroupAggregate and Filter: (count(adjustment_id) &gt; 1)</li></ul><h4>Understanding key words</h4><p><strong>Estimation of execution of a node</strong>: After each node we can see two parentheses. The first one is an estimation provided by the planner: (cost=140239785.58..141500120.46 rows=504133952 width=16)</p><p><strong>Actual statistics of execution of a node</strong>: The second parentheses contains actual stats after executing the node. This information is returned by the executor, not the planner: (actual time=86675.662..206504.852 rows=134377 loops=1)</p><p><strong>Cost</strong>: This is not in milliseconds. It is an arbitrary unit based on some parameters configured in PostgreSQL. seq_page_cost is conventionally set to 1.0 and the other cost parameters are set relative to that. You can execute these queries if you want to see the values of some parameters:</p><pre>SHOW seq_page_cost; -- sequentiel cost (default: 1.0) <br>SHOW random_page_cost; -- random cost (default: 4.0) <br>SHOW cpu_tuple_cost; -- cost of reading a line (default: 0.01) <br>SHOW cpu_index_tuple_cost; -- cost of reading an index (default: 0.005) <br>SHOW cpu_operator_cost; -- cost of cpu oprtation (default: 0.0025</pre><p>In our example we have cost=140239785.58..141500120.46</p><ul><li>The first value is the startup cost; it determines how much it’s going to take to fetch the first row.</li><li>The value after .. is total cost; it determines how much it’s going to take to fetch all the rows.</li></ul><p><strong>Rows</strong>: In the estimated part, this is the number of rows estimated to be returned by the node. In the actual part, this is the real number of rows returned when executing the node.</p><p><strong>Width</strong>: The estimated size occupied by each line, here it’s equal to 16 bytes because we are returning two columns of type bigint (8 bytes each). This information is important because we can use it to calculate the size of our result set, which is the number of lines multiplied by the width. In our example 134377*16 = 2 MB.</p><p><strong>Loops</strong>: Number of times the operation was executed</p><p><strong>Heap Fetches</strong>: The number where it was necessary to access the table during the index only scan. This operation is performed if the table is not vacuumed.</p><p>Vacuum consists of cleaning the frozen lines on a table. When we perform delete in PostgreSQL, lines are marked as removed but are not truly deleted. This is done after a vacuum.</p><p>PostgreSQL has a data structure called “Visibility Map”. The VM tells us whether all the lines of a table are visible to all transactions or not. A VM is updated by delete operations and vacuum. When delete operation occurs the VM equivalent is marked as not visible until the vacuum is executed.</p><p>In our case, Heap Fetches was done because the executor consulted the visibility map and saw that some lines are not visible, thus it was necessary to check the table for 788294 lines to see if they exist or not. If the vacuum was performed before, Heap fetches would be = 0.</p><p><strong>Sort Method: external merge Disk</strong>: The Executor performs an external merge when there isn’t enough work_mem available to perform the sort operation entirely in memory.</p><p>rows × width × overhead = Memory needed 504,133,952 × 16 bytes × ~1.1 = ~8.9 GB</p><h3>Comparison between estimated and actual statistics</h3><p>Query 1 (with COUNT(adjustment_id)):</p><pre>GroupAggregate<br>- Estimated rows: 158,293,619<br>- Actual rows: 134,377<br><strong>- Accuracy: Off by ~99.92%<br></strong><br>Sort<br>- Estimated rows: 504,133,952<br>- Actual rows: 504,035,748<br><strong>- Accuracy: Off by ~0.02%<br></strong><br>Seq Scan<br>- Estimated rows: 504,133,952<br>- Actual rows: 504,035,748<br><strong>- Accuracy: Off by ~0.02%</strong></pre><p>Query 2 (with COUNT(*)):</p><pre>GroupAggregate<br>- Estimated rows: 163,294,901<br>- Actual rows: 134,368<br><strong>- Accuracy: Off by ~99.92%<br></strong><br>Index Only Scan<br>- Estimated rows: 506,419,104<br>- Actual rows: 506,246,363<br><strong>- Accuracy: Off by ~0.03%</strong></pre><p>GroupAggregate row estimation is significantly off Base scan estimations are very accurate</p><h4>Why the Differences:</h4><ul><li>Statistics limitations for complex operations</li><li>Lack of detailed statistics about data distribution</li></ul><p>This analysis helps us understand:</p><ul><li>Where the planner needs better statistics</li><li>Which operations are harder to estimate</li><li>How accurate the base table statistics are</li></ul><p>We can update the table statisitcs with Analyse command.</p><h4>What ANALYZE Does:</h4><ol><li>Samples the table data</li><li>Updates statistics about:</li></ol><ul><li>Number of distinct values in each column</li><li>Most common values and their frequencies</li><li>Data distribution statistics</li><li>Correlation between physical and logical row ordering</li></ul><h3>Conclusion</h3><p>Understanding execution plans is essential for query optimization. The key is to:</p><ul><li>Know how to read and interpret the plans</li><li>Understand different scan types and their implications</li><li>Recognize when estimates are accurate or not</li><li>Maintain database statistics and indexes properly</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=310799b30c4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hexagonal Architecture]]></title>
            <link>https://medium.com/@anassguendef/hexagonal-architecture-df13ef7dd3cf?source=rss-2f0c7102fced------2</link>
            <guid isPermaLink="false">https://medium.com/p/df13ef7dd3cf</guid>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Anass Guendef]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 17:32:21 GMT</pubDate>
            <atom:updated>2022-12-02T17:32:21.412Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7FKGeTD3RGmcdzzF" /><figcaption>Photo by <a href="https://unsplash.com/@dotnny?utm_source=medium&amp;utm_medium=referral">Donny Jiang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Definition</h3><p>The main characteristic of “Hexagonal Architecture”, as opposed to the common layered style of architecture, is that the dependencies between our components point “inwards”, towards our domain objects.</p><p>The point is to isolate the core business of an application and test its behavior independently of all the rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymvS50t1_tRNpeEEcyHifQ.png" /></figure><h3>Three principles</h3><p>The hexagonal architecture is based on three principles:</p><ul><li>Explicit separation: Application, Domain, and Infrastructure.</li><li>Dependencies go to Domain.</li><li>Ports and Adapters isolate domain boundaries.</li></ul><h3>Domain</h3><ul><li>The Domain is the core business of the application; it contains the business objects as well as the business rules.</li><li>Domain Objects have no external dependencies, they are pure Java (POJO).</li><li>Because domain objects do not depend on other layers of the application, changes from other layers do not affect them.</li><li>Isolation of the Domain from technical dependencies will allow us to ensure maximum test coverage of the business.</li><li>Ideally, a business expert who does not know how to code could read a piece of code from this part and tell us about an inconsistency.</li><li>Domain objects and use cases reside in the hex, i.e. in the core of the application, every communication to and from outside goes through dedicated “ports”.</li><li>An input port is a simple interface that can be called by external components and implemented. The component calling such an input port is called an input adapter (a Rest API, for example).</li><li>An output port is still a simple interface that our use cases can call if they need something from the outside (access to a database, for example). it is implemented by an external component called an output adapter.</li></ul><h3>Application</h3><ul><li>The entry point of our application. It contains the code that allows the interaction of the user or the external programs with the application.</li><li>This is the side where we find the actors who <strong>pilot </strong>the Domain.</li><li>It contains the input adapters.</li></ul><h3>Infrastructure</h3><ul><li>We put in it what our application needs to work, the essential infrastructure details like the code that interacts with the database, with a partner, with the file system…</li><li>This is the side where we find the actors who are <strong>driven </strong>by the Domain.</li><li>It contains the output adapters.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtKqrxJ2H7xmZYURKxatlQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df13ef7dd3cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ToString() by Java Reflection]]></title>
            <link>https://medium.com/@anassguendef/tostring-by-java-reflection-3356e6aa2a59?source=rss-2f0c7102fced------2</link>
            <guid isPermaLink="false">https://medium.com/p/3356e6aa2a59</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-reflection]]></category>
            <dc:creator><![CDATA[Anass Guendef]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 13:06:44 GMT</pubDate>
            <atom:updated>2022-11-22T16:53:06.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*7xgh-vqFRMP68_QvsXMdrw.png" /></figure><p>In some cases, we need to know the content of a java object that is an instance of class that we could not edit, a class from an imported jar for example.</p><p>As we know, The ToString() method, defined in Object class, can give us the name of the class and his address in memory. This method can be overridden, so we can add more details about the object’s content.</p><p>Let consider the following PersonFromExternalJar class :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7feb3901c3e1d425ca17b795d91500ac/href">https://medium.com/media/7feb3901c3e1d425ca17b795d91500ac/href</a></iframe><p>As we can see, the toString() method is defined but commented out. Let consider also that PersonFromExternalJar class is coming from an external jar, and we cannot edit it.</p><p>In this case, we can still have the possibility to print the content of the object person by using Java Reflection.</p><p>The utility class <a href="https://commons.apache.org/proper/commons-lang//apidocs/src-html/org/apache/commons/lang3/builder/ReflectionToStringBuilder.html#line.103">ReflectionToStringBuilder</a> from Apache commons-lang3 uses reflection to determine the fields to append and their values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85dc3a7c39c65caab1cd488f7c2702d9/href">https://medium.com/media/85dc3a7c39c65caab1cd488f7c2702d9/href</a></iframe><p>Running the above class will print the following :</p><pre>PersonFromExternalJar@2a139a55<br>PersonFromExternalJar@2a139a55[firstName=Said,lastName=ALAOUI,age=33]</pre><p>As a bonus, you can also get the content of nested object using this method :</p><pre>ToStringBuilder.reflectionToString(person, new RecursiveToStringStyle());</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3356e6aa2a59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequence desynchronization]]></title>
            <link>https://medium.com/@anassguendef/sequence-desynchronization-26a05fcc1d83?source=rss-2f0c7102fced------2</link>
            <guid isPermaLink="false">https://medium.com/p/26a05fcc1d83</guid>
            <category><![CDATA[sequence]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Anass Guendef]]></dc:creator>
            <pubDate>Mon, 24 Oct 2022 22:36:33 GMT</pubDate>
            <atom:updated>2022-10-25T09:08:30.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DlVIRS0fKjpXw8kv" /><figcaption>Photo by <a href="https://unsplash.com/@yogidan2012?utm_source=medium&amp;utm_medium=referral">Daniele Levis Pelusi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s subject, I am going to present a classic problem when dealing with databases that use sequences. It’s about “Sequence desynchronization”.</p><p>Let start by defining a sequence. A sequence is a database feature that creates unique values by incrementing the old ones. It is important to emphasize that multiple transactions cannot get the same sequence value.</p><p>Sequence desynchronization, happens usually when database backup or restore fails to set sequences, when we set the sequence value incorrectly, or when we specify the id’s value manually.</p><blockquote>When Sequence desynchronization occurs in PostgreSQL, it returns “duplicate key value violates unique constraint” error.</blockquote><p>To solve this problem in PostgreSQL, we need to set the values of desynchronized sequences using the max(id) of concerned tables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/197f6b0925291bc53f17aab68806b868/href">https://medium.com/media/197f6b0925291bc53f17aab68806b868/href</a></iframe><p>You can also fix all the sequences by constructing the query above for all the sequences in database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b52284adfb31ea7841989dfca55f6c28/href">https://medium.com/media/b52284adfb31ea7841989dfca55f6c28/href</a></iframe><p>All you need to do after that, is executing the resulting script.</p><blockquote>It’s important to mention that the sequence must follow the PostgreSQL’s notation :</blockquote><blockquote>table-name_column-name_seq</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26a05fcc1d83" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>